KEMBAR78
01 introduction to entity framework | PPTX
Adam Tuliper | Technical Evangelist, Microsoft
Christopher Harrison | Content Developer, Microsoft
Meet Adam Tuliper | @AdamTuliper
• Technical Evangelist, Microsoft
– Focused on Web, Data, Gaming, and Cloud Technologies
– Emphasis on secure development practices
• 20 years of industry experience as software architect
– Enterprise, startups, public sector, defense, healthcare, financial
industries
– channel9.msdn.com/Blogs/AdamTuliper
• Video content
– adamtuliper.com
Meet Christopher Harrison | @geektrainer
Content Developer
Focused on ASP.NET and Office 365 development
Microsoft Certified Trainer
Regular presenter at TechEd
Long time geek
Still misses his Commodore 64
Periodic blogger (blog.geektrainer.com)
Marathoner, husband, father of one four legged child
Setting Expectations
• Target Audience
–Web Developers
–Experience with C#
• Suggested Prerequisites/Supporting Material
–Introduction to MVC
• Microsoft Virtual Academy
– Free online learning tailored for IT Pros and Developers
– Over 2.6 million registered users
– Up-to-date, relevant training on variety of Microsoft products
• “Earn while you learn!”
– Get 50 MVA Points for this event!
– Visit http://aka.ms/MVA-Voucher
– Enter this code: MVCEntityFrmwrk (Expires 2Mar15)
Join the MVA Community!
Github Repository
• Has all demo files along with slides from this session
• http://github.com/MicrosoftLearning/EntityFramework
Course Topics
Implementing Entity Framework with MVC
01 | Introduction to Entity Framework 04 | Managing the database
02 | Beginning Code First 05 | Managing transactions
03 | Managing Relationships
06 | Integrating extra features and looking
forward
01 | Introduction to Entity Framework
Adam Tuliper | Technical Evangelist, Microsoft
Christopher Harrison | Content Developer, Microsoft
Module Overview
• Architecture
• Intro to Code First
• Generating EF Classes
Architecture
What is the Entity Framework
• It IS an ORM
• What’s an ORM?
– Maps your database types to your code types
– Avoids repetitive data access code
Customer Customer.cs
Customer
CustomerInfo.cs
ShipTo
EF Platforms
• EF 6.1 Any project that is full .NET 4+
• All Microsoft SQL Databases
• Web Forms, MVC, WPF, WCF, Web API, Web Forms
• Newer ones to include Azure Table Storage, Redis, Linux, etc
• Supported ADO.NET Providers
– https://msdn.microsoft.com/en-us/data/dd363565.aspx
Some supported features
• Full ORM to map objects to code
• Async Queries
• Connection Resiliency (retry)
• Stored Procedure mapping
• Reverse engineering existing database
• Using code to create database (code first)
• Concurrency detection
• Enum & Spatial Data support
High level view
• Simplified View
LINQ to Entities
Convert to
query, execute
Map results to
entities
EF System Components
Installing Entity Framework
• EF6 Requires Visual Studio 2010 or greater
• NuGet
– Install-package EntityFramework
• Comes as part of
– MVC, Web Forms, Web API templates if Identity is used
NuGet Primer
• Install-Package EntityFramework
– Latest non-beta
• Install-Package EntityFramework –pre
– pre release version
• Uninstall-Package EntityFramework
• Update-Package EntityFramework –reinstall (all projects)
• Update-Package EntityFramework -ProjectName MyProject
DEMODEMO
Installing and Managing Entity Framework Binaries
Intro to Code First
Code First
• The term ‘code first’ – a misnomer?
• Maps your POCO classes to database
• Uses at a minimum a DbContext and an entity (ie a class)
public class MusicStoreDbContext : DbContext
{
public DbSet<Album> Albums{ get; set; }
}
public class Album
{
public string Name { get; set; }
public decimal Cost{ get; set; }
}
DbContext
POCO (Entity)
DEMODEMO
Basic code first and scaffolding
public MusicContext() : base("MusicStoreConnection")
{
}
How does EF connect to your db?
• Could be cloud, App_Data folder, Intranet, Internet, other folder
Use context class name
to look for connect
string in web.config
No connect string.
Start database checks
Read connect string
Open Connection
Connect string named in
DbContext class
Look for SQL Express Look for (localdb)11
Look for
(localdb)mssqllocaldb
Read connect string
Open Connection
You should always specify a connection
string name when you intend to use a
connection string in the config file. This
ensures that if the connection string is
not present then Entity Framework will
throw rather than creating a new
database by convention.
<add name="MusicStoreContext" connectionString="Data
Source=(localdb)v12.0;.." providerName="System.Data.SqlClient" />
Helpful Hint
• Connecting to LocalDb be aware of instance names
– Typically v11.0, mssqllocaldb
– ProjectsV12 is created by data tools, ignore
• Connection string
– Data Source=(localdb)mssqllocaldb;
• Get versions / instances via
– sqllocaldb i
– sqllocaldb v
Viewing queries
• context.Database.Log = s => Console.WriteLine(s);
• Glimpse
– Install-package glimpse.mvc5
– install-package glimpse.ef6
• Interceptors
– Goes in .config
<interceptors>
<interceptor
type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger,
EntityFramework">
<parameters>
<parameter value=“MyAppsOutput.txt"/>
<parameter value="true" type="System.Boolean"/>
</parameters>
</interceptor>
</interceptors>
DEMODEMO
Viewing queries and connection info
Generating EF classes
Ways to generate
• Hand coding classes
• Use a visual designer
• Add->ADO.NET Entity Data Model
• Database First Entity Designer
DEMODEMO
Generating database and reverse engineering
Resources
• EF Resources
– https://msdn.microsoft.com/en-us/data/ef.aspx
• EF Team Blog
– http://blogs.msdn.com/b/adonet/
©2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the
U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft
must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the
U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft
must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

01 introduction to entity framework

  • 1.
    Adam Tuliper |Technical Evangelist, Microsoft Christopher Harrison | Content Developer, Microsoft
  • 2.
    Meet Adam Tuliper| @AdamTuliper • Technical Evangelist, Microsoft – Focused on Web, Data, Gaming, and Cloud Technologies – Emphasis on secure development practices • 20 years of industry experience as software architect – Enterprise, startups, public sector, defense, healthcare, financial industries – channel9.msdn.com/Blogs/AdamTuliper • Video content – adamtuliper.com
  • 3.
    Meet Christopher Harrison| @geektrainer Content Developer Focused on ASP.NET and Office 365 development Microsoft Certified Trainer Regular presenter at TechEd Long time geek Still misses his Commodore 64 Periodic blogger (blog.geektrainer.com) Marathoner, husband, father of one four legged child
  • 4.
    Setting Expectations • TargetAudience –Web Developers –Experience with C# • Suggested Prerequisites/Supporting Material –Introduction to MVC
  • 5.
    • Microsoft VirtualAcademy – Free online learning tailored for IT Pros and Developers – Over 2.6 million registered users – Up-to-date, relevant training on variety of Microsoft products • “Earn while you learn!” – Get 50 MVA Points for this event! – Visit http://aka.ms/MVA-Voucher – Enter this code: MVCEntityFrmwrk (Expires 2Mar15) Join the MVA Community!
  • 6.
    Github Repository • Hasall demo files along with slides from this session • http://github.com/MicrosoftLearning/EntityFramework
  • 7.
    Course Topics Implementing EntityFramework with MVC 01 | Introduction to Entity Framework 04 | Managing the database 02 | Beginning Code First 05 | Managing transactions 03 | Managing Relationships 06 | Integrating extra features and looking forward
  • 8.
    01 | Introductionto Entity Framework Adam Tuliper | Technical Evangelist, Microsoft Christopher Harrison | Content Developer, Microsoft
  • 9.
    Module Overview • Architecture •Intro to Code First • Generating EF Classes
  • 10.
  • 11.
    What is theEntity Framework • It IS an ORM • What’s an ORM? – Maps your database types to your code types – Avoids repetitive data access code Customer Customer.cs Customer CustomerInfo.cs ShipTo
  • 12.
    EF Platforms • EF6.1 Any project that is full .NET 4+ • All Microsoft SQL Databases • Web Forms, MVC, WPF, WCF, Web API, Web Forms • Newer ones to include Azure Table Storage, Redis, Linux, etc • Supported ADO.NET Providers – https://msdn.microsoft.com/en-us/data/dd363565.aspx
  • 13.
    Some supported features •Full ORM to map objects to code • Async Queries • Connection Resiliency (retry) • Stored Procedure mapping • Reverse engineering existing database • Using code to create database (code first) • Concurrency detection • Enum & Spatial Data support
  • 14.
    High level view •Simplified View LINQ to Entities Convert to query, execute Map results to entities EF System Components
  • 15.
    Installing Entity Framework •EF6 Requires Visual Studio 2010 or greater • NuGet – Install-package EntityFramework • Comes as part of – MVC, Web Forms, Web API templates if Identity is used
  • 16.
    NuGet Primer • Install-PackageEntityFramework – Latest non-beta • Install-Package EntityFramework –pre – pre release version • Uninstall-Package EntityFramework • Update-Package EntityFramework –reinstall (all projects) • Update-Package EntityFramework -ProjectName MyProject
  • 17.
    DEMODEMO Installing and ManagingEntity Framework Binaries
  • 18.
  • 19.
    Code First • Theterm ‘code first’ – a misnomer? • Maps your POCO classes to database • Uses at a minimum a DbContext and an entity (ie a class) public class MusicStoreDbContext : DbContext { public DbSet<Album> Albums{ get; set; } } public class Album { public string Name { get; set; } public decimal Cost{ get; set; } } DbContext POCO (Entity)
  • 20.
  • 21.
    public MusicContext() :base("MusicStoreConnection") { } How does EF connect to your db? • Could be cloud, App_Data folder, Intranet, Internet, other folder Use context class name to look for connect string in web.config No connect string. Start database checks Read connect string Open Connection Connect string named in DbContext class Look for SQL Express Look for (localdb)11 Look for (localdb)mssqllocaldb Read connect string Open Connection You should always specify a connection string name when you intend to use a connection string in the config file. This ensures that if the connection string is not present then Entity Framework will throw rather than creating a new database by convention. <add name="MusicStoreContext" connectionString="Data Source=(localdb)v12.0;.." providerName="System.Data.SqlClient" />
  • 22.
    Helpful Hint • Connectingto LocalDb be aware of instance names – Typically v11.0, mssqllocaldb – ProjectsV12 is created by data tools, ignore • Connection string – Data Source=(localdb)mssqllocaldb; • Get versions / instances via – sqllocaldb i – sqllocaldb v
  • 23.
    Viewing queries • context.Database.Log= s => Console.WriteLine(s); • Glimpse – Install-package glimpse.mvc5 – install-package glimpse.ef6 • Interceptors – Goes in .config <interceptors> <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework"> <parameters> <parameter value=“MyAppsOutput.txt"/> <parameter value="true" type="System.Boolean"/> </parameters> </interceptor> </interceptors>
  • 24.
  • 25.
  • 26.
    Ways to generate •Hand coding classes • Use a visual designer • Add->ADO.NET Entity Data Model • Database First Entity Designer
  • 27.
  • 28.
    Resources • EF Resources –https://msdn.microsoft.com/en-us/data/ef.aspx • EF Team Blog – http://blogs.msdn.com/b/adonet/
  • 29.
    ©2013 Microsoft Corporation.All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION. ©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes

  • #2 1
  • #13 Talk about nuget packages, upgrading, rolling back, etc. IBM supplies ADO.NET data providers for access to DB2, Informix, and U2 databases. Any ADO.NET Data Provider?
  • #17 Update-Package -Reinstall (reinstall all packages in all projects)
  • #18 Create MVC app without identity, Install-package entityframework Create MVC app with identity, show it already exists. Show how to upgrade, remove, reinstall. Update-Package EntityFramework (maybe –pre if theres time)
  • #21 Create a new console app, then we’ll do web. Install-package EF Add class public class Album { public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } } public class MusicContext : DbContext { public DbSet<Album> Albums { get; set; } } 4. Run the app. Explain the database is created because of connection string in the name in DbContext 5. If DbContext doesn’t have a connect string, we look for the name of the context class connection string. If that’s not found, we try to create SQLExpress, local db 12, local db 11 6. Add a connection string and show that new database using (var context = new MusicContext()) { var albums = context.Albums.ToList(); Console.WriteLine(albums.Count()); context.Albums.Add(new Album() { AlbumArtUrl="http://no.com", AlbumId=1, ArtistId=1, GenreId=2, Price=9.99m, Title="My Album"}); context.SaveChanges(); albums = context.Albums.ToList(); Console.WriteLine(albums.Count()); }
  • #22 DB name will be that of the connection string name, ie Data Source=(localdb)\mssqllocaldb;Initial Catalog=MusicStoreConnection;Integrated Security=True public MusicContext() : base("MusicStoreConnection") { } <connectionStrings> <add name="MusicStoreContext" connectionString="Data Source=(localdb)\v12.0; Initial Catalog=MusicStoreDev; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|MusicStoreDev.mdf" providerName="System.Data.SqlClient" /> </connectionStrings>
  • #24 <interceptors>   <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">     <parameters>       <parameter value=“MyAppsOutput.txt"/>       <parameter value="true" type="System.Boolean"/>     </parameters>   </interceptor> </interceptors>
  • #25 //View queries context.Database.Log = s => Console.WriteLine(s); //Log connection Console.WriteLine(context.Database.Connection.ConnectionString); Using glimpse Install-package glimpse.mvc5 install-package glimpse.entityframework Inside the <entityFramework> element <interceptors>   <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">     <parameters>       <parameter value=“MyAppsOutput.txt"/>       <parameter value="true" type="System.Boolean"/>     </parameters>   </interceptor> </interceptors>
  • #27 Discuss manual method, deprecating the designer, and revere engineering
  • #28 Look briefly at dialog Choose an existing database with music store information in it and reverse engineer it. Discuss we’ll talk about the database more in module 4