Entity Framework Database and Code First


Published on

Slide deck presented to LA SQL Developers Group on Thursday, March 15, 2012

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Entity Framework Database and Code First

  1. 1. James Johnson, MVP
  2. 2.  Founder and President of the Inland Empire .NET User’s Group Three time and current Microsoft MVP – CAD Software developer by day Serial netrepreneur by night
  3. 3.  Entity Framework Database First Code First MVC Scaffolding
  4. 4.  Version 4 released with .NET 4.0 New version (4.3) allows for model-first, code-first or database-first development Maps POCO objects to database objects A collection of things instead of a dataset of rows “things” are the entities
  5. 5.  Why? ◦ Adds a layer of abstraction between database and code ◦ DBA can structure database how they want ◦ Developer can map to the database how they want ◦ Rename entities for more comfortable use ◦ Entity Framework handles the mappings
  6. 6.  Entity Data Model – EDM ◦ Deals with the entities and relationships they use Entities ◦ Instance of EntityType  Specification for a data type which includes a key and named set of properties ◦ Represent individual instances of the objects ◦ Customer, book, shoe, usergroup ◦ Fully typed Relationships between look up tables are mapped as associations in the EDMX
  7. 7.  csdl ◦ Conceptual Schema Definition Language ◦ The conceputal schema for the EDM ◦ EntityContainer, EntitySet, EntityType definitions ssdl ◦ Store Schema Definition Language ◦ Schematic representation of the data store msl ◦ Mapping Specification Language ◦ Sits between the csdl and ssdl and maps the entity properties
  8. 8. Lazy LoadingA design pattern to defer initialization until neededcontext.ContextOptions.DeferredLoadingEnabled=true;List<Member> members = context.Members.ToList();foreach(var member in members){ var memberBooks = member.Books;}
  9. 9. Eager LoadingUse if you will be needing every related entityList<Member> Members = context.Members.Include(“Books”).ToList();foreach(var member in members){ var memberBooks = member.Books;}
  10. 10. Contexts The context is the instance of the entity Passing an entity around to tiers breaks the context Just like the song, make sure the context remains the same
  11. 11. Contextspublic class ModelHelper{ private static Entities _db; public static Entities Entities { get { if(_db == null) _db = new Entities(); return _db; } set { _db = value; } } }private readonly Entities _db = new Entities();
  12. 12. Contextsprivate Member AddMember(Member member, UserGroup group){ member.UserGroups.Add(group); _db.SaveChanges();} Doesn’t work because group is in a different contextprivate Member AddMember(Member member, UserGroup group){ var newMember = GetMember(member.Id); var newGroup = GetUserGroup(group.Id); newMember.UserGroups.Add(newGroup); _db.SaveChanges();}
  13. 13. LINQ to EntitiesVery similar to LINQ to SQLSelectingMember member = _db.Members.Single(x=>x.Id == id);Deletingpublic void DeleteMember(Member member){ _db.DeleteObject(member); _db.SaveChanges();}
  14. 14. LINQ to EntitiesAdding (Inserting)public void AddMember(Member member){ _db.AddToMembers(member) //this will be a list _db.SaveChanges() // of AddTo<Entities>}Editing (Updating)public void EditMember(Member member){ _db.Members.Attach(new Member{Id=member.Id}); _db.Members.ApplyCurrentValues(member); _db.SaveChanges();}
  15. 15. Repositories Repository pattern encapsulates code into a separate class Allows for easy changes Can use it to switch database providers or new technologies Stephen Walther – ASP.NET MVC Framework, Sams ◦ stephenwalther.com ◦ “Download the code” link Add the two projects to your solution Add references to your project
  16. 16. Repositoriesusing GenericRepositorypublic class MyController{ private readonly IGenericRepository _repo; private readonly Entities _db; public MyController() { _repo = new EFGenericRepository.EFGenericRepository(_db); }}
  17. 17. Repositories_repo.Get<Member>(id); // get_repo.Edit(member); // edit_repo.Create(member); // create_repo.Delete(member); // delete// listvar list = _repo.List<Member>().Where(x => x.Name.Contains(myName));
  18. 18. Database First Create the database first Build tables and relationships Create Entity Data Model (EDMX) in Visual Studio Look up tables are converted to Associations
  19. 19. Database First
  20. 20. Database First Members_Books UserGroups_Members Associations representing look up tables
  21. 21. Demo
  22. 22. Code First – The “Magic Unicorn” Write code without having to define mappings in XML Define objects in POCO No base classes required Enables database persistence with no configuration Can use Data Annotations ◦ Key ◦ StringLength ◦ Required ◦ RelatedTo ◦ Etc. DbContext ◦ Primary object to interact with a database using specific model DbSet<TEntity> ◦ Used to perform CRUD against a specific type from the model
  23. 23. Code First Create classes Create Context Create Controller Write code for ◦ Select ◦ Add ◦ Update ◦ Delete Create Views
  24. 24. Databases By default, creates SQL Express DB ◦ <Project>.Models.<Project>Context.mdf Can switch to SQL Compact1. NuGet2. Search for SqlServerCompact3. InstallAdds System.Data.SqlServerCe to references
  25. 25. Databases  Add connection string settings to web.config  Name needs to match context<add name=“UserGroups”connectionString=“Data Source=|DataDirectory|UserGroups.sdf”providerName=“System.Data.SqlServerCe.4.0” />
  26. 26. Databases Run the project UserGroups.sdf will be created
  27. 27. Databases – Keeping Current Modifying the database Add setting to Global.asax Implementation of IDatabaseInitializer Deletes and recreates the database
  28. 28. Databases – Keeping Current EF 4.3.1 uses Code First Migrations ◦ Enabled by default ◦ Adds table __MigrationHistory to database Only modifies database if model has changed
  29. 29. Demo
  30. 30. Scaffolding Create MVC project Use NuGet to update EntityFramework Package Manager Console “Install-Package MvcScaffolding”
  31. 31. Scaffolding Add Class(es) Build Project
  32. 32. Scaffolding Package Manager Console “Scaffold Controller <ClassName>
  33. 33. Scaffolding Controller and Views are created
  34. 34. Scaffolding – Other Commands -ControllerName ◦ UserGroupsController – look for class “UserGroup” ◦ UserGroup – creates UserGroupsController -ModelType ◦ Inferred from controller name ◦ Can change name of the model if needed -Project ◦ Specify the name of the project in multi-project solutions -CodeLanguage ◦ Specify “cs” or “vb” -DbContextType ◦ Specify the name of the context
  35. 35. Scaffolding – Other Commands -Repository ◦ Switch. Will generate a repository class for data access -Area ◦ For putting the generated files in a specific MVC Area -Layout ◦ Which layout page to use if not default _Layout.cshtml -Force ◦ Forces overwriting of existing files -NoChildItems ◦ Will only generate the controller, no views, repositories or data contexts
  36. 36. Scaffolding  Add connection string settings to web.config  Name needs to match context<add name=“UserGroupsScaffoldingContext”connectionString=“Data Source=|DataDirectory|UserGroups.sdf”providerName=“System.Data.SqlServerCe.4.0” />
  37. 37. Scaffolding Run the project Navigate to /UserGroups/ Database is created
  38. 38. Scaffolding Scaffold the rest of the classes “Scaffold Controller <ClassName> Run the project Database will be modified with new tables
  39. 39. Scaffolding
  40. 40. Scaffolding Relationships It’s not you, it’s me. Add relationships to your classes Using virtual allows EF to use Lazy Loading
  41. 41. Scaffolding Relationships Run the project again Database is modified Look up tables are created
  42. 42.  Slides are at ◦ http://slidesha.re/EFScaffolding Inland Empire .NET User’s Group ◦ 2nd Tuesday of each month ◦ www.iedotnetug.org james@iedotnetug.org @latringo