KEMBAR78
Entity framework and how to use it | PPTX
Entity Framework 4& How touseitPascal FransenApril 2011Nspyre Technology Group .NETwww.nspyre.net
OverviewEntity Framework
Introduction
Features
Code first
Demo : Forms
Model first
Demo : Console
Generate From database
Tiny Introduction MVC3
Tiny Introduction Razor
Demo : EF4/MVC3/razor
Questions2
EntityFramework - introduction3
EntityFramework – introduction – new features4POCO Support: You can now define entities without requiring base classes or data persistence attributes.
Lazy Loading Support: You can now load sub-objects of a model on demand instead of loading them up front.
N-Tier Support and Self-Tracking Entities: Handle scenarios where entities flow across tiers or stateless web calls.
Better SQL Generation and SPROC support: EF4 executes better SQL, and includes better integration with SPROCs
Automatic Pluralization Support: EF4 includes automatic pluralization support of tables (e.g. Categories->Category).
Improved Testability: EF4’s object context can now be more easily faked using interfaces.
Improved LINQ Operator Support: EF4 now offers full support for LINQ operators. Entity Framework – Code FirstAddreferences via Tools -> Library Package Manager -> Package Manager ConsoleIn console type install-package entityframeworkReferenceswillbeaddedautomatically5
EntityFramework – Code First -Create data classes sets and contextCreate ClassesAddreferencestoother classes (virtual)CreateDbContextwithDbSet ‘s6usingSystem.Data.Entity;namespaceEntityCodeFirst{public class Restaurant : DbContext    {public DbSet<Table> Tables { get; set; }public DbSet<Client> Clients { get; set; }    }}public class Client{public string Name { get; set; }public string Phone { get; set; }public DateTime Time { get; set; } public virtual Table Table { get; set; }}public class Table{public string Name { get; set; }public intMaxClients { get; set; }public virtual ICollection<Client> Clients{ get; set; } }
Entity Framework – Code First - Addconnection stringAddto web / app.config :<?xmlversion="1.0" encoding="utf-8" ?><configuration>  <connectionStrings>    <add name="Restaurant"connectionString="Server=.\SQLEXPRESS;Database=Restaurant;Trusted_Connection=True;"providerName="System.Data.SqlClient" />  </connectionStrings></configuration>7
Entity Framework – Code First - DemoDemo8

Entity framework and how to use it

  • 1.
    Entity Framework 4&How touseitPascal FransenApril 2011Nspyre Technology Group .NETwww.nspyre.net
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
    EntityFramework – introduction– new features4POCO Support: You can now define entities without requiring base classes or data persistence attributes.
  • 16.
    Lazy Loading Support:You can now load sub-objects of a model on demand instead of loading them up front.
  • 17.
    N-Tier Support andSelf-Tracking Entities: Handle scenarios where entities flow across tiers or stateless web calls.
  • 18.
    Better SQL Generationand SPROC support: EF4 executes better SQL, and includes better integration with SPROCs
  • 19.
    Automatic Pluralization Support:EF4 includes automatic pluralization support of tables (e.g. Categories->Category).
  • 20.
    Improved Testability: EF4’sobject context can now be more easily faked using interfaces.
  • 21.
    Improved LINQ OperatorSupport: EF4 now offers full support for LINQ operators. Entity Framework – Code FirstAddreferences via Tools -> Library Package Manager -> Package Manager ConsoleIn console type install-package entityframeworkReferenceswillbeaddedautomatically5
  • 22.
    EntityFramework – CodeFirst -Create data classes sets and contextCreate ClassesAddreferencestoother classes (virtual)CreateDbContextwithDbSet ‘s6usingSystem.Data.Entity;namespaceEntityCodeFirst{public class Restaurant : DbContext {public DbSet<Table> Tables { get; set; }public DbSet<Client> Clients { get; set; } }}public class Client{public string Name { get; set; }public string Phone { get; set; }public DateTime Time { get; set; } public virtual Table Table { get; set; }}public class Table{public string Name { get; set; }public intMaxClients { get; set; }public virtual ICollection<Client> Clients{ get; set; } }
  • 23.
    Entity Framework –Code First - Addconnection stringAddto web / app.config :<?xmlversion="1.0" encoding="utf-8" ?><configuration> <connectionStrings> <add name="Restaurant"connectionString="Server=.\SQLEXPRESS;Database=Restaurant;Trusted_Connection=True;"providerName="System.Data.SqlClient" /> </connectionStrings></configuration>7
  • 24.
    Entity Framework –Code First - DemoDemo8
  • 25.
    Entity Framework –Model FirstClass Library projectAdd New Item : ADO.NET Entity Data ModelSelect : Empty modelUse Right-click or Toolboxtoadd:EntitiesAssociationsInheritanceAlways use ‘createkey property’9
  • 26.
    Entity Framework –Model First - AssociationsChoose nameSet multiplicityAddforeignkey:willautomaticallyadd IdsReferentialconstraint is added10
  • 27.
    Entity Framework –Model First - Generateto databaseDatabase Generation Workflow Default : TablePerTypeStrategy.xaml(VS)More availablefromPowerPackGenerate Database from ModelA database must existChoose Data ConnectionDDL is generatedandsavedPut it in your source controlApp.config is addedCheck the tablenames … 11
  • 28.
    Entity Framework- ModelFirst - Use model projectAddreferenceto model projectAddconnectionstringtoApp.configOr just copy-paste itwhen emptyAddreferencetoSystem.Data.Entity var context = new ModelFirstDemo.FirstModelContainer();varquery = from c in context.PersonSet select c;foreach(Person p in query.ToList()){Console.WriteLine(p.Name);}12
  • 29.
    Entity Framework- ModelFirst - DemoDemo13
  • 30.
    Entity Framework –new MVC ProjectAdd ASP.NET MVC3 Web ApplicationChoose : EmptyView Engine : RazorAddreferences:ToentityprojectToSystem.Data.EntityInsertconnectionstringintoWeb.Config14
  • 31.
    MVC3 - TinyIntroductionClean Separation of Concerns, where each component is serving only one purpose. Thus it also gives us the opportunity to integrate TDD (Test-Driven Development) in the development workflow and unit test each component without considering the others, as most of the framework components are interface-based. This allows us to mock them out.The whole framework is very much extensible and pluggable. It is really easy to replace or customize each part without affecting the others.Pretty/SEO (Search Engine Optimization) URLs. Full controls of how URLs are constructed. No need to do URL Rewriting anymore.True stateless model of the web. We no longer have to deal with postbacksand ViewState.Full control of the generated HTML. Utilize the existing knowledge of ASP.NET like Providers, Caching,Configuration 15
  • 32.
    MVC3 – TinyRazorintroductionAlternativefor asp.net view engineClean coding modelIntegratesnicelywith HTML‘Master Page’-like features16<p>My name is @View.Name and I live at @View.Address</p>Compare this to the equivalent using the aspx view engine<p>My name is <%:View.Name %> and I live at <%: View.Address %></p>
  • 33.
    Entity Framework -Database First -Generatefrom databaseChoosegeneratefrom database17
  • 34.
    MVC3 - Addcontroller and viewModel is available in entity projectController puts data in ViewViews canbeaddedby right-clicking the ActionResultView name is generatedChooseRazor view engineCreate a strongly-typed view ->18
  • 35.
    MVC3 – buildthe viewSomehow, the view does notknowabout the Entity Framework, soaddtoweb.config<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>Model passedthroughconstructorModel properties are availablewithinrazor view19
  • 36.
    MVC3 – listsand editingNew controller withgenerated Action methodsChoose the entityandscaffoldtemplate:CreateDeleteDetailsEditEmptyList20
  • 37.
    Model First -Stored ProceduresRight-click object andchooseAllthree CUD procedures must bemapped21
  • 38.
  • 39.
    ReferencesEntity Frameworkhttp://msdn.microsoft.com/en-us/data/aa937723MVC 3http://www.asp.net/mvc/mvc3http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part1-csEntityDesigner Database Generation Power Packhttp://visualstudiogallery.msdn.microsoft.com/df3541c3-d833-4b65-b942-989e7ec74c87/NuGet package managementhttp://nuget.codeplex.com/23
  • 40.