.NET Database Technologies: Entity Framework additional notes – part 2

download .NET Database Technologies:  Entity Framework additional notes – part 2

of 25

  • date post

  • Category


  • view

  • download


Embed Size (px)


.NET Database Technologies: Entity Framework additional notes – part 2. EF1 => EF4. “The 1.0 release of the Entity Framework was not a resounding success – developers found themselves fighting the framework” EF4 gives you the choice of how to work Database-first, model-first, code-first - PowerPoint PPT Presentation

Transcript of .NET Database Technologies: Entity Framework additional notes – part 2

  • .NET Database Technologies: Entity Frameworkadditional notes part 2

  • EF1 => EF4The 1.0 release of the Entity Framework was not a resounding success developers found themselves fighting the frameworkEF4 gives you the choice of how to workDatabase-first, model-first, code-firstSupports POCO entities for Persistence Ignorance

  • POCO supportEF1 entity classes inherit from EntityObjectDifficult to separate concerns in applicationClasses are difficult to unit testFor unit testing, want to fake persistent storageDifficult to switch DAL technologyCant take existing classes and use EF1 Need to redesign classes significantly to bind them to EFEF4 allows you to use POCOsModel classes can be completely ignorant of persistence mechanism

  • POCO classesPOCO classes must work in conjunction with EDMMust mirror entities defines in EDMHowever, EDM does not generate the classesSet Code Generation Strategy to none in designer propertiesTwo ways to create classesWrite POCO code by handUse a T4 TemplateMicrosoft ADO.NET C# POCO Entity GeneratorDownload from www.visualstudiogallery.comRight-click EDM designer surface and select Add Code Generation ItemCreates template for generating POCOs to match EDM

  • T4Text Template Transformation ToolkitCode generation tool built into Visual StudioCan be used in many different code generation scenariosTemplate file has .tt extensionWhen a project has a .tt file, the template is processed at build timeGenerated code file(s) associated with template in Solution Explorer, but can be moved elsewhere if required

  • Managing POCOsNeed to create a custom ObjectContext classShould have an ObjectSet for each entity typeNeeds to know name of EDMX file (passed in as a constructor parameter) to allow it to access mapping and storage information

  • Issues with POCOs change trackingChange trackingClasses derived from EntityObject constantly communicate with ObjectContextPOCOs cant do thisObjectContext has to track changes to POCOs: DetectChanges methodSaveOptions -> DetectAllChanges forces call to DetectChanges before savingDefault behaviour

  • Issues with POCOs loading related dataEntityObject can load related data with Load methode.g. employee.AddressesReference.Load()Navigation property also has an EntityReference property POCO does not have EntityReference propertiesNeed to load related data from contexte.g. context.LoadProperty( employee, e => e.Addresses)Can also support lazy loading with POCOs through dynamic proxies (see later)

  • Issues with POCOs two-way relationshipsContext forces EntityObject classes to be aware of two-way relationships and keeps relationships in syncOptions for doing this with POCOs:Call DetectChanges method of contextWrite code in POCO classes so that they manage their own relationshipsUse dynamic proxies

  • Dynamic proxiesPOCO classes can be wrapped by proxy classes which are created dynamically at runtimeProxy class is derived from POCO classPOCO properties must be marked as virtualAdds EF-specific behaviour which allows management of change tracking, lazy-loading and relationships in the same way as EntityObject classesClient code works with POCO classes, but actual objects instantiated are proxiesEF uses reflection to find out about properties of POCOs and Reflection.Emit to dynamically generate IL code for proxy classes

  • POCOs and PIPOCOs do not need to derive from any persistence specific classDo not use persistence specific collection typesShould use ICollection as collection property typeRequirement for properties to be virtual to support some capabilities through proxiesThis does not violate PI classes dont need to know about what the derived classes will doEF4 POCO support allows PI domain classes to be used

  • Using a repositoryRather than having client code query context directly it is common to use a repositoryA repository Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects (Fowler)Promotes testability Can swap in fake context with affecting client/test codeCan program client to an interface for repository and define actual repository type through dependency injectionAllows DAL to be swapped easilyContext implements Unit of Work pattern, but often wrap this in UoW class/interface to allow further isolation of dependencies

  • IoC and Dependency InjectionInversion of Control (IoC) Objects do not create other objects on which they rely to do their workInstead, they get the objects that they need from an outside source (for example, an xml configuration file)Dependency Injection (DI) This is done without the object intervention, usually by a container that passes constructor parameters and set propertiesCastle Windsor is an example of a .NET DI containerCan manage dependencies for all kinds of service, not just persistencehttp://msdn.microsoft.com/en-us/library/aa973811.aspx

  • Creating a repositoryPattern describes solution to problem, but does not strictly define how to write the codeMany variations on the Repository pattern are possibleYou can design your own there are plenty of articles and blog posts with examples to base it onYou can use a template to generate your basic implementation from an EDMADO.NET Unit Testable Repository GeneratorDownload from www.visualstudiogallery.comEFRepositoryDownload from efrepository.codeplex.com

  • Model-FirstAll examples so far have been re-engineered from the databaseChanges to the conceptual model were mapped to the original databaseEF4 allows you to start by designing the conceptual model and then use that model to define the databaseModel-First

  • Creating the conceptual modelAdd new ADO.NET Entity Data Model item to project and select Empty Data Model in wizardAdd new Entities to model using Toolbox or right-click on designer surfaceAdd properties (scalar or complex) to each entity by right-clicking on entitySet type of property in Properties windowGive each entity a key propertyAdd associations by right-clicking on surface or entitiesAdding association creates navigation propertiesCreate inheritance hierarchy by specifying base class for new entities

  • Generate databaseRight-click on designer surface and select Generate Database from the ModelSlightly misleading nameDatabase must exist designer will generate DDL to add to databaseDesigner does not execute the DDL script it creates have to do that separatelyDDL Generation wizard allows you to specify the database, and creates connection string in app.configWizard adds SSDL and MSL portions to EDMX file and creates SQL script in project folder

  • DDL generationBased on a T4 templateTable names come from EntitySet namesProperty and association attributes set in designer will be reflected in column attributes, e.g. data types, cascade deleteInheritance will be implemented with a TPT strategyMany-to-many relationship implemented with a join table

  • Customising DDL generationPossible to modify T4 template Only template installed in VS2010 is SSDL to SQL 10.ttOr use Entity Designer Database Generation Power PackDownload from www.visualstudiogallery.comContains additional templatesCan force TPH strategy for inheritanceProvides capability to migrate existing database after making changes to model

  • Model-First and POCOsModel-First approach is compatible with POCOsOnce EDMX has been created, you can create POCOs to mirror entities and ObjectContext class to manage themAlternatively, the entities you create in the designer can be based on knowledge of existing POCO classes

  • Code-FirstAvoid altogether working with visual model Build your model with POCO classesMoving towards true Domain Driven DesignMicrosoft consulted with a Data Programmability Advisory Council which included Fowler, Evans and NilssonCurrently this feature is a CTP, not included in the release of VS2010Need to download and installAdd reference to Microsoft.Data.Entity.Ctp.dll which is installed in Program Files\Microsoft ADO.NET Entity Framework Feature CTP5\BinariesAdd using System.Data.Entity where required

  • What does Code-First do?You need to create POCOs and a context class which inherits from DbContextDefines DbSet property to store a set of each entity classAt runtime it reads your class definitions and creates in-memory representation of CSDL, MSL and SSDLLooks for connection string that has the same name as the context classUses convention-based persistence mappingConvention over configurationCreates database if it doesnt already exist (SQL CE and SQL Express)

  • Customising mappingOverride OnModelCreating event of DbContext and use ModelBuilder class to customise mappingChange table namesCustomise column/property mappingSplit a table across multiple typeshttp://weblogs.asp.net/scottgu/archive/2010/07/23/entity-framework-4-code-first-custom-database-schema-mapping.aspxData annotation attributesSpecify keys, string lengths, etchttp://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx

  • EF4 options - summaryDatabase-FirstDefine model and mappings in EDMXEntities are EntityObjects or POCOsModel-FirstDefine model in EDMXEntities are EntityObjects or POCOsCode-FirstDefine model with POCOsMappings defined by convention or ModelBuilder/annotationsEntities are POCOs

  • Profiling EFProfile at serverSQL Server ProfilerProfile at clientEF Profilerhttp://efprof.com/Not free!