NYCEntity FrameworkFirestarter
Speakers
Entity Framework FirestarterSchedule
Thanks MicrosoftFor Hosting and Lunch
EF NYC FirestarterPart 1:   It’s Time to Look at Entity FrameworkJulie Lermanthedatafarm.com/blogtwitter @julielerman
Julie LermanwebsitetheDataFarm.comblog & twittertheDataFarm.com/blog@julielermanbook web siteLearnEntityFramework.comconsultant/mentorMicrosoft MVP, INETA Speaker,ASPInsider, MCP, VTdotNET LeaderNYC Entity Framework Firestarter, Sept 27th 2010
Why Entity Framework?NYC Entity Framework Firestarter, Sept 27th 2010Object Relational MapperADO.NETDataSetADORecordSetEntityFrameworkObjectSpaces
Design Time: EDMXEF Metadata vs Other ORMsNYC Entity Framework Firestarter, Sept 27th 2010DBDBEF Runtime Metadata (XML files)Conceptual ModelSchemaDatabaseStructureSchemaDesigner Layout & PositioningTypical ORMObjects
ADO.NET Today & TomorrowNYC Entity Framework Firestarter, Sept 27th 2010DataSetEntity FrameworkLINQ to SQL
Model in Entity FrameworkModelFirstDatabaseFirstNewDatabaseLegacyDatabaseCodeFirstNYC Entity Framework Firestarter, Sept 27th 2010“M”
Entity FrameworkConceptual Model in your AppsUIDBConceptualModelof your DomainApp LogicProviderQueryTrack ChangesRepositoryUpdates to DBBusinessObjectsNYC Entity Framework Firestarter, Sept 27th 2010
Time to CodeA little modeling…A little querying…A little editing…A little saving…NYC Entity Framework Firestarter, Sept 27th 2010
FAQSStored Procedure SupportUse Views & Stored Procs – no table accessUpdate the model when DB changesMappings are highly customizableInheritanceMany to ManyMerge tablesSplit tablesetcPass through queries & commandsNYC Entity Framework Firestarter, Sept 27th 2010
Entity Framework EverywhereNYC Entity Framework Firestarter, Sept 27th 2010
Why Entity Framework SummaryMicrosoft’s in-the-box ORMFocus of Microsoft/.NET data accessUse any back end db (with a provider)Use in any type of .NET applicationBackbone of many Microsoft technologiesNYC Entity Framework Firestarter, Sept 27th 2010
 Part 2:What’s new in Entity Framework 4EF NYC FirestarterSteve Bohlenunhandled-exceptions.com/blogtwitter @sbohlen
Long Form: ComprehensiveNYC Entity Framework Firestarter, Sept 27th 2010Model-first developmentAutomatic pluralizationForeign keys in modelsPOCO class supportLazy loadingT4 Code GenerationTemplate customizationIObjectSetVirtual SaveChangesObjectStateManagercontrolSelf-tracking entitiesSQL generation improvementsMore LINQ operator supportLINQ extensibilityExecuteStoreQueryExecuteStoreCommandSPROC import improvementsModel defined functionsWPF designer integrationCode-First development (Feature CTP)
Short Form: HighlightsDesigner ImprovementsForeign KeysNew Code GenerationPersistence IgnoranceChange Tracking for WCFBetter n-tier SupportLazy LoadingCode-Only Development
Designer ImprovementsPluralization SupportGenerate Database from Modelvs. only Reverse-Engineering in v1Improved SPROC SupportSPROCs can return only entities in v1SPROCs can return strongly-typed projections in v4
Foreign Key SupportERM vs exposed FKs (it’s a CHOICE via the dialog box)Does NOT replace the Nav propertiesDataContext is able to leverage this for some efficienciesChanging either the FK or the Nav property changes the other value (due to code-gen support)
Code GenerationModel  templates  ClassesCode Generation Engine now T4 instead of proprietary engine in v1Tools support/syntax support resources review a quick look at the T4 syntaxT4 Editor add-in
(better) Persistence IgnoranceEntityObject inheritance NOT requiredSnapshot-basedNo lazy loading support in this approachNo Change Trackingmust call ObjectContext.DetectChanges( )ObjectContext.Save( ) implicitly calls .DetectChanges( )Proxy-basedvirtual keyword is the ‘flag’ for this behaviorvirtual on all  change-tracking and lazy-loadvirtual on just navigation props  only lazy-loadingSeveral Canned Templates
WCF and Self-Tracking EntitiesT4 template for self-tracking entitiesPassing objects across serialization boundaries
Lazy Loadingv1 supported only explicit load of lazy collectionsObjectContext.ContextOptions.LazyLoadingEnabled = trueby default in NEW models, but NOT in imported v1 modelsBehavior scoped at the ObjectContextNOT at property level for entitiesToggle-able before and after operations for query-specific granular lazy-loading behavior
Explicit State ManagementObjectContext.ApplyCurrentValues( )Formerly ApplyPropertyChanges( ) in v1ObjectContext.ApplyOriginalValues( )ObjectStateEntry.ChangeState( )Unchanged/Added/Modified/DeletedObjectStateManager.ChangeRelationshipState( )
Code-Only Support‘Feature CTP’Classes  EntitiesEntities  Database (optionally)No Model NecessaryHeavily Convention over Configuration
MiscellaneousModel-Defined FunctionsObjectSet (collections of entities)Complex Type SupportQuery optimization (E-SQL, LINQ2Entities)ExecuteCommand/Defined Queries/Model FunctionsDesigner support for more features without direct editing of .csdl, .ssdl, .edml
 Part 4:    Getting Started with POCOs in EF4EF NYC FirestarterJulie Lermanthedatafarm.com/blogtwitter @julielerman
AgendaSimple POCO ClassesLeveraging ProxiesCustomizable T4 Code GenerationNYC Entity Framework Firestarter, Sept 27th 2010
POCOPlain Old CLR Objects
BenefitsUse existing classesLoose CouplingClasses have no dependency on EFPersistence IgnoranceUnit TestingRepositories & Unit Of Work Patterns
ObjectContext Manages EntitiesNYC Entity Framework Firestarter, Sept 27th 2010POCO“Snapshot”4.0EntityObject(3.5 & 4.0)ObjectContextPerson ObjectState infoState infoOrder ObjectState infoDetail ObjectState infoDetail ObjectState infoOrder ObjectState infoDetail ObjectState infoDetail Object
POCO Support BasicsTurn off code generation from EDMX“Convention” will auto-map classes/entitiesNYC Entity Framework Firestarter, Sept 27th 2010
POCO and Other EF FeaturesComplex TypesUse a class (no structs) to represent the typeExplicit LoadingObjectContext.LoadProperty(myObj,”PropertyName”)ObjectContext.LoadProperty(myObj, o=>o.property)Two-Way NavigationMust be coded into classesNYC Entity Framework Firestarter, Sept 27th 2010
Lazy Loading POCOsvirtual (Overridable) navigation properties IRelatedEnd wrapper at run-timeLazyLoadingEnabled=true requiredSelectively allow lazy loaded propertiespublicList<CreditCard>CreditCards {get; set; }virtualpublicPersonPerson {get;set; }publicList<Order> Orders { get;set; }
ObjectContext Manages EntitiesNYC Entity Framework Firestarter, Sept 27th 2010POCO“Snapshot”4.0POCO+ Dynamic Runtime Proxy (4.0)EntityObject(3.5 & 4.0)ObjectContextPerson ObjectState infoState infoOrder ObjectState infoDetail ObjectState infoDetail ObjectState infoOrder ObjectState infoDetail ObjectState infoDetail Object
Dynamic Runtime Proxy Classes Track
Lazy Load
RelationshipsPersonclassF5Mark all Entity (model) Properties virtualProvides features similar to EntityObjectChange notificationRelationship managementLazy Loading
Rules for Proxy NotificationAll entity properties shall be virtualThough shalt use ICollection<T>Creation shall be done withObjectContext.CreateObject<T>Classes shall not be sealedNavigation properties shall not be sealedClasses shall not be abstract          Classes shall have a parameter-less constructor
Code Gen POCOs from ModelT4T4Text Template Transformation Toolkit
EF POCO SummaryPOCO support is new to EF4Alternative to EntityObjectsSimple snapshot POCOs or use proxiesUse or even customize T4 template for code generationEnable many coding/architectural possibilitiesNYC Entity Framework Firestarter, Sept 27th 2010
 Part 5:    Disconnected Strategies for     ASP.NET & ServicesEF NYC FirestarterJulie Lermanthedatafarm.com/blogtwitter @julielerman
AgendaEF Challenges in Server ApsReview Options with EFEF4 Tools to the RescuePOCOs and RepositoriesLeveraging Foreign KeysPutting it all together
Change Tracking Across TiersObjectContextObjectStateEntrySO1 EntityKey Original ValuesCurrent Values Other ∆ Info ObjectStateEntrySO2 EntityKeyOriginal ValuesCurrent ValuesOther ∆ Info detachentitiesObjectStateEntryLIA EntityKeyOriginal ValuesCurrent ValuesOther ∆ Info Original  Property ValuesEntityState ValuesObjectStateEntryLIB EntityKeyOriginal ValuesCurrent ValuesOther ∆ Info
SaveChanges Fails Across Post BacksPage RequestPost Back #1Post Back #2New Page ClassNew Page ClassNew Page ClassCreate New ObjectContextCreate  NewObjectContextCreate  NewObjectContextGet EntitiesProcess RequestGet EntitiesBuild HTML using Data & ASP.NET MarkupBuild HTML using Data & ASP.NET MarkupBuild HTML using Data & ASP.NET MarkupDestroy Page and DependentsDestroy Page and DependentsDestroy Page and Dependents
The Server Side Spectrum with EFDynamic Data forEntitiesObjectDataSourceWCF &Self-Tracking EntsEntityDataSourceMVCWCFDataServicesDevWCFASP.NETn-TierArchitect
EF4 Changes to the RescueForeign KeysBig help for selected list values on postbackState MethodsApplyCurrentValues, ApplyOriginalValuesChangeStateChangeRelationshipState (when no FKs)POCO Classes & T4 GenerationSelf-Tracking Entities for use with WCF
What about?GraphsLazy LoadingReturning IQueryablesChangeTracking
NYC Entity Framework Firestarter, Sept 27th 2010Oh, goody….time for code…
Disconnected Strategies SummaryEF has inherent challenges across tiersNew tools in EF4 to enable disconnectedNYC Entity Framework Firestarter, Sept 27th 2010
 Part 6:Writing Testable/Maintainable Apps with EFEF NYC FirestarterSteve Bohlenunhandled-exceptions.com/blogtwitter @sbohlenJulie Lermanthedatafarm.com/blogtwitter @julielerman
AgendaSetting the stageRefactor a demo-worthy MVC appExplore an existing solution with more complexity
“-ilities”Benefits:ExtensibilityAdaptabilityTestabilityMaintainabilityQuality Why should You Care?Persistence Ignorance (PI)Future-Proofing your investmentNYC Entity Framework Firestarter, Sept 27th 2010
IObjectSet AbstractionIObjectSetCollection-like behaviorAdd, Attach, Delete, etc.ObjectSetConcrete classImplements IObjectSetInherits ObjectQuerypublic class ObjectSet:ObjectQuery,IObjectSet
EF4 Goodness Makes This WorkNYC Entity Framework Firestarter, Sept 27th 2010POCOs+T4 Code GenDisconnected MethodsIObjectSet

Entity Framework NYC Firestarter

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
    EF NYC FirestarterPart1: It’s Time to Look at Entity FrameworkJulie Lermanthedatafarm.com/blogtwitter @julielerman
  • 6.
    Julie LermanwebsitetheDataFarm.comblog &twittertheDataFarm.com/blog@julielermanbook web siteLearnEntityFramework.comconsultant/mentorMicrosoft MVP, INETA Speaker,ASPInsider, MCP, VTdotNET LeaderNYC Entity Framework Firestarter, Sept 27th 2010
  • 7.
    Why Entity Framework?NYCEntity Framework Firestarter, Sept 27th 2010Object Relational MapperADO.NETDataSetADORecordSetEntityFrameworkObjectSpaces
  • 8.
    Design Time: EDMXEFMetadata vs Other ORMsNYC Entity Framework Firestarter, Sept 27th 2010DBDBEF Runtime Metadata (XML files)Conceptual ModelSchemaDatabaseStructureSchemaDesigner Layout & PositioningTypical ORMObjects
  • 9.
    ADO.NET Today &TomorrowNYC Entity Framework Firestarter, Sept 27th 2010DataSetEntity FrameworkLINQ to SQL
  • 10.
    Model in EntityFrameworkModelFirstDatabaseFirstNewDatabaseLegacyDatabaseCodeFirstNYC Entity Framework Firestarter, Sept 27th 2010“M”
  • 11.
    Entity FrameworkConceptual Modelin your AppsUIDBConceptualModelof your DomainApp LogicProviderQueryTrack ChangesRepositoryUpdates to DBBusinessObjectsNYC Entity Framework Firestarter, Sept 27th 2010
  • 12.
    Time to CodeAlittle modeling…A little querying…A little editing…A little saving…NYC Entity Framework Firestarter, Sept 27th 2010
  • 13.
    FAQSStored Procedure SupportUseViews & Stored Procs – no table accessUpdate the model when DB changesMappings are highly customizableInheritanceMany to ManyMerge tablesSplit tablesetcPass through queries & commandsNYC Entity Framework Firestarter, Sept 27th 2010
  • 14.
    Entity Framework EverywhereNYCEntity Framework Firestarter, Sept 27th 2010
  • 15.
    Why Entity FrameworkSummaryMicrosoft’s in-the-box ORMFocus of Microsoft/.NET data accessUse any back end db (with a provider)Use in any type of .NET applicationBackbone of many Microsoft technologiesNYC Entity Framework Firestarter, Sept 27th 2010
  • 16.
     Part 2:What’s newin Entity Framework 4EF NYC FirestarterSteve Bohlenunhandled-exceptions.com/blogtwitter @sbohlen
  • 17.
    Long Form: ComprehensiveNYCEntity Framework Firestarter, Sept 27th 2010Model-first developmentAutomatic pluralizationForeign keys in modelsPOCO class supportLazy loadingT4 Code GenerationTemplate customizationIObjectSetVirtual SaveChangesObjectStateManagercontrolSelf-tracking entitiesSQL generation improvementsMore LINQ operator supportLINQ extensibilityExecuteStoreQueryExecuteStoreCommandSPROC import improvementsModel defined functionsWPF designer integrationCode-First development (Feature CTP)
  • 18.
    Short Form: HighlightsDesignerImprovementsForeign KeysNew Code GenerationPersistence IgnoranceChange Tracking for WCFBetter n-tier SupportLazy LoadingCode-Only Development
  • 19.
    Designer ImprovementsPluralization SupportGenerateDatabase from Modelvs. only Reverse-Engineering in v1Improved SPROC SupportSPROCs can return only entities in v1SPROCs can return strongly-typed projections in v4
  • 20.
    Foreign Key SupportERMvs exposed FKs (it’s a CHOICE via the dialog box)Does NOT replace the Nav propertiesDataContext is able to leverage this for some efficienciesChanging either the FK or the Nav property changes the other value (due to code-gen support)
  • 21.
    Code GenerationModel templates  ClassesCode Generation Engine now T4 instead of proprietary engine in v1Tools support/syntax support resources review a quick look at the T4 syntaxT4 Editor add-in
  • 22.
    (better) Persistence IgnoranceEntityObjectinheritance NOT requiredSnapshot-basedNo lazy loading support in this approachNo Change Trackingmust call ObjectContext.DetectChanges( )ObjectContext.Save( ) implicitly calls .DetectChanges( )Proxy-basedvirtual keyword is the ‘flag’ for this behaviorvirtual on all  change-tracking and lazy-loadvirtual on just navigation props  only lazy-loadingSeveral Canned Templates
  • 23.
    WCF and Self-TrackingEntitiesT4 template for self-tracking entitiesPassing objects across serialization boundaries
  • 24.
    Lazy Loadingv1 supportedonly explicit load of lazy collectionsObjectContext.ContextOptions.LazyLoadingEnabled = trueby default in NEW models, but NOT in imported v1 modelsBehavior scoped at the ObjectContextNOT at property level for entitiesToggle-able before and after operations for query-specific granular lazy-loading behavior
  • 25.
    Explicit State ManagementObjectContext.ApplyCurrentValues()Formerly ApplyPropertyChanges( ) in v1ObjectContext.ApplyOriginalValues( )ObjectStateEntry.ChangeState( )Unchanged/Added/Modified/DeletedObjectStateManager.ChangeRelationshipState( )
  • 26.
    Code-Only Support‘Feature CTP’Classes EntitiesEntities  Database (optionally)No Model NecessaryHeavily Convention over Configuration
  • 27.
    MiscellaneousModel-Defined FunctionsObjectSet (collectionsof entities)Complex Type SupportQuery optimization (E-SQL, LINQ2Entities)ExecuteCommand/Defined Queries/Model FunctionsDesigner support for more features without direct editing of .csdl, .ssdl, .edml
  • 28.
     Part 4: Getting Started with POCOs in EF4EF NYC FirestarterJulie Lermanthedatafarm.com/blogtwitter @julielerman
  • 29.
    AgendaSimple POCO ClassesLeveragingProxiesCustomizable T4 Code GenerationNYC Entity Framework Firestarter, Sept 27th 2010
  • 30.
  • 31.
    BenefitsUse existing classesLooseCouplingClasses have no dependency on EFPersistence IgnoranceUnit TestingRepositories & Unit Of Work Patterns
  • 32.
    ObjectContext Manages EntitiesNYCEntity Framework Firestarter, Sept 27th 2010POCO“Snapshot”4.0EntityObject(3.5 & 4.0)ObjectContextPerson ObjectState infoState infoOrder ObjectState infoDetail ObjectState infoDetail ObjectState infoOrder ObjectState infoDetail ObjectState infoDetail Object
  • 33.
    POCO Support BasicsTurnoff code generation from EDMX“Convention” will auto-map classes/entitiesNYC Entity Framework Firestarter, Sept 27th 2010
  • 34.
    POCO and OtherEF FeaturesComplex TypesUse a class (no structs) to represent the typeExplicit LoadingObjectContext.LoadProperty(myObj,”PropertyName”)ObjectContext.LoadProperty(myObj, o=>o.property)Two-Way NavigationMust be coded into classesNYC Entity Framework Firestarter, Sept 27th 2010
  • 35.
    Lazy Loading POCOsvirtual(Overridable) navigation properties IRelatedEnd wrapper at run-timeLazyLoadingEnabled=true requiredSelectively allow lazy loaded propertiespublicList<CreditCard>CreditCards {get; set; }virtualpublicPersonPerson {get;set; }publicList<Order> Orders { get;set; }
  • 36.
    ObjectContext Manages EntitiesNYCEntity Framework Firestarter, Sept 27th 2010POCO“Snapshot”4.0POCO+ Dynamic Runtime Proxy (4.0)EntityObject(3.5 & 4.0)ObjectContextPerson ObjectState infoState infoOrder ObjectState infoDetail ObjectState infoDetail ObjectState infoOrder ObjectState infoDetail ObjectState infoDetail Object
  • 37.
    Dynamic Runtime ProxyClasses Track
  • 38.
  • 39.
    RelationshipsPersonclassF5Mark all Entity(model) Properties virtualProvides features similar to EntityObjectChange notificationRelationship managementLazy Loading
  • 40.
    Rules for ProxyNotificationAll entity properties shall be virtualThough shalt use ICollection<T>Creation shall be done withObjectContext.CreateObject<T>Classes shall not be sealedNavigation properties shall not be sealedClasses shall not be abstract Classes shall have a parameter-less constructor
  • 41.
    Code Gen POCOsfrom ModelT4T4Text Template Transformation Toolkit
  • 42.
    EF POCO SummaryPOCOsupport is new to EF4Alternative to EntityObjectsSimple snapshot POCOs or use proxiesUse or even customize T4 template for code generationEnable many coding/architectural possibilitiesNYC Entity Framework Firestarter, Sept 27th 2010
  • 43.
     Part 5: Disconnected Strategies for ASP.NET & ServicesEF NYC FirestarterJulie Lermanthedatafarm.com/blogtwitter @julielerman
  • 44.
    AgendaEF Challenges inServer ApsReview Options with EFEF4 Tools to the RescuePOCOs and RepositoriesLeveraging Foreign KeysPutting it all together
  • 45.
    Change Tracking AcrossTiersObjectContextObjectStateEntrySO1 EntityKey Original ValuesCurrent Values Other ∆ Info ObjectStateEntrySO2 EntityKeyOriginal ValuesCurrent ValuesOther ∆ Info detachentitiesObjectStateEntryLIA EntityKeyOriginal ValuesCurrent ValuesOther ∆ Info Original Property ValuesEntityState ValuesObjectStateEntryLIB EntityKeyOriginal ValuesCurrent ValuesOther ∆ Info
  • 46.
    SaveChanges Fails AcrossPost BacksPage RequestPost Back #1Post Back #2New Page ClassNew Page ClassNew Page ClassCreate New ObjectContextCreate NewObjectContextCreate NewObjectContextGet EntitiesProcess RequestGet EntitiesBuild HTML using Data & ASP.NET MarkupBuild HTML using Data & ASP.NET MarkupBuild HTML using Data & ASP.NET MarkupDestroy Page and DependentsDestroy Page and DependentsDestroy Page and Dependents
  • 47.
    The Server SideSpectrum with EFDynamic Data forEntitiesObjectDataSourceWCF &Self-Tracking EntsEntityDataSourceMVCWCFDataServicesDevWCFASP.NETn-TierArchitect
  • 48.
    EF4 Changes tothe RescueForeign KeysBig help for selected list values on postbackState MethodsApplyCurrentValues, ApplyOriginalValuesChangeStateChangeRelationshipState (when no FKs)POCO Classes & T4 GenerationSelf-Tracking Entities for use with WCF
  • 49.
  • 50.
    NYC Entity FrameworkFirestarter, Sept 27th 2010Oh, goody….time for code…
  • 51.
    Disconnected Strategies SummaryEFhas inherent challenges across tiersNew tools in EF4 to enable disconnectedNYC Entity Framework Firestarter, Sept 27th 2010
  • 52.
     Part 6:Writing Testable/MaintainableApps with EFEF NYC FirestarterSteve Bohlenunhandled-exceptions.com/blogtwitter @sbohlenJulie Lermanthedatafarm.com/blogtwitter @julielerman
  • 53.
    AgendaSetting the stageRefactora demo-worthy MVC appExplore an existing solution with more complexity
  • 54.
    “-ilities”Benefits:ExtensibilityAdaptabilityTestabilityMaintainabilityQuality Why shouldYou Care?Persistence Ignorance (PI)Future-Proofing your investmentNYC Entity Framework Firestarter, Sept 27th 2010
  • 55.
    IObjectSet AbstractionIObjectSetCollection-like behaviorAdd,Attach, Delete, etc.ObjectSetConcrete classImplements IObjectSetInherits ObjectQuerypublic class ObjectSet:ObjectQuery,IObjectSet
  • 56.
    EF4 Goodness MakesThis WorkNYC Entity Framework Firestarter, Sept 27th 2010POCOs+T4 Code GenDisconnected MethodsIObjectSet