EF Object ServicesEyal VardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com
AgendaEF ArchitectureDevelopment ApproachesEntity Data Model (EDM)Object ServicesQuerying & Loading EntitiesEDMLINQ to EntitiesEntity SQLConceptual ModelObject ServicesMappingEntity Client ProviderStorageModelADO.NET Provider
Services:- Change tracking- Concurrency control- Object identitySQL or Stored ProcsRowsSQLServerEntity FrameworkEF ArchitectureApplicationfrom c in db.Customerswhere c.City == "London"select new { c.Name, c.Phone }ObjectsLINQ QuerySubmitChanges()EDMXADO.NET ProviderSQL Queryselect Name, Phonefrom customerswhere city = 'London'
EF ArchitectureSQLServerEDMLINQ to EntitiesEntity SQLConceptual ModelObject ServicesMappingEntity Client ProviderStorageModelADO.NET Provider
Object ServicesMaterialization The process of transforming the data obtained from the Entity Client data provider, which has a tabular structure, into objects. Change tracking Tracks any changes made to the objects.Query transformationTranslates queries it into a command tree that’s then passed on to the underlying Entity Client.Object identitiesObject Services FunctionsQueryingQuerying data as objects Shaping query results Composing queriesCRUD Lazy loadingInheritanceNavigating relationshipChange tracking Saving changesAttaching objectsDetaching objects Serializing objectsManagingObject identitiesConcurrencyTransactions
LINQ to Entities (Finding)DbSet and IDbSet implement IQueryable.DbSetand IDbSet always create queries against the databasealways involve a round trip to the database even if the entities returned already exist in the context.
Finding an Entity by Primary KeyLook on the contextA round-trip to the database will only be made if the entity with the given key is not found in the context.
Eagerly LoadingEager loading is the process whereby a query for one type of entity also loads related entities as part of the query.
Eagerly Loading (multiple levels)It is also possible to eagerly load multiple levels of related entities.
Lazy LoadingPOCO Properties Must be Virtual.Configuration.LazyLoadingEnabled = true;
Explicitly LoadingEven with lazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call.
Explicitly Loading
Count Related Entities Without Loading Them
Local DataThe Local property of DbSetprovides simple access to the entities of the set that are currently being tracked by the context and have not been marked as Deleted. Accessing the Local property never causes a query to be sent to the database.
No Tracking QueriesSometimes you may want to get entities back from a query but not have those entities be tracked by the context. Better performance Read-only scenarios
Entity States & Save ChangesEntity states before & After Save Changes.
Adding a New Entity to the Context
Adding a New Entity to the ContextAdd a new entity to the context by hooking it up to another entity that is already being tracked.
Attaching an Existing Entity to the ContextEntity that already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet.
Original & Current Values
Marking a Property as ModifiedMarking a property as modified forces an update to be send to the database for the property when SaveChanges is called even if the current value of the property is the same as its original value.
Current values: Property Id has value 1 Property Name has value FrankyProperty Version has value System.Byte[] Property PrincessId has value 1 Original values: Property Id has value 1 Property Name has value BinkyProperty Version has value System.Byte[] Property PrincessId has value 1 Database values: Property Id has value 1 Property Name has value Squeaky Property Version has value System.Byte[] Property PrincessId has value 1
Setting Values From Another ObjectCurrent values: Property Id has value 1 Property Name has value Rapunzel Original values: Property Id has value 1 Property Name has value Rosannella
Getting & Setting Complex Pro’s
Dynamic ProxiesWhen creating instances of POCO entity types, the EF often creates instances of a dynamically generated derived type that acts as a proxy for the entity. This proxy overrides some virtual properties of the entity to insert hooks for performing actions automatically when the property is accessed.Configuration.ProxyCreationEnabled = true;
Creating an Instance of a ProxyThe Create method does not add or attach the created entity to the context.If the entity type is sealed and/or has no virtual properties then Create will just create an instance of the entity type.
Automatically Detecting ChangesDbContext automatically detecting changes when the following methods are called:DbSet.FindDbSet.LocalDbSet.RemoveDbSet.AddDbSet.AttachDbContext.SaveChangesDbContext.GetValidationErrorsDbContext.EntryDbChangeTracker.Entries
Disabling Auto Detecting Changesperformance improvementsAn alternative to disabling and re-enabling is to leave automatic detection of changes turned off at all times and either call context.ChangeTracker.DetectChangesexplicitly.
Entity Framework -  Object Services

Entity Framework - Object Services

  • 1.
    EF Object ServicesEyalVardiCEO E4D Solutions LTDMicrosoft MVP Visual C#blog: www.eVardi.com
  • 2.
    AgendaEF ArchitectureDevelopment ApproachesEntityData Model (EDM)Object ServicesQuerying & Loading EntitiesEDMLINQ to EntitiesEntity SQLConceptual ModelObject ServicesMappingEntity Client ProviderStorageModelADO.NET Provider
  • 3.
    Services:- Change tracking-Concurrency control- Object identitySQL or Stored ProcsRowsSQLServerEntity FrameworkEF ArchitectureApplicationfrom c in db.Customerswhere c.City == "London"select new { c.Name, c.Phone }ObjectsLINQ QuerySubmitChanges()EDMXADO.NET ProviderSQL Queryselect Name, Phonefrom customerswhere city = 'London'
  • 4.
    EF ArchitectureSQLServerEDMLINQ toEntitiesEntity SQLConceptual ModelObject ServicesMappingEntity Client ProviderStorageModelADO.NET Provider
  • 5.
    Object ServicesMaterialization Theprocess of transforming the data obtained from the Entity Client data provider, which has a tabular structure, into objects. Change tracking Tracks any changes made to the objects.Query transformationTranslates queries it into a command tree that’s then passed on to the underlying Entity Client.Object identitiesObject Services FunctionsQueryingQuerying data as objects Shaping query results Composing queriesCRUD Lazy loadingInheritanceNavigating relationshipChange tracking Saving changesAttaching objectsDetaching objects Serializing objectsManagingObject identitiesConcurrencyTransactions
  • 6.
    LINQ to Entities(Finding)DbSet and IDbSet implement IQueryable.DbSetand IDbSet always create queries against the databasealways involve a round trip to the database even if the entities returned already exist in the context.
  • 7.
    Finding an Entityby Primary KeyLook on the contextA round-trip to the database will only be made if the entity with the given key is not found in the context.
  • 8.
    Eagerly LoadingEager loadingis the process whereby a query for one type of entity also loads related entities as part of the query.
  • 9.
    Eagerly Loading (multiplelevels)It is also possible to eagerly load multiple levels of related entities.
  • 10.
    Lazy LoadingPOCO PropertiesMust be Virtual.Configuration.LazyLoadingEnabled = true;
  • 11.
    Explicitly LoadingEven withlazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call.
  • 12.
  • 13.
    Count Related EntitiesWithout Loading Them
  • 14.
    Local DataThe Localproperty of DbSetprovides simple access to the entities of the set that are currently being tracked by the context and have not been marked as Deleted. Accessing the Local property never causes a query to be sent to the database.
  • 15.
    No Tracking QueriesSometimesyou may want to get entities back from a query but not have those entities be tracked by the context. Better performance Read-only scenarios
  • 16.
    Entity States &Save ChangesEntity states before & After Save Changes.
  • 17.
    Adding a NewEntity to the Context
  • 18.
    Adding a NewEntity to the ContextAdd a new entity to the context by hooking it up to another entity that is already being tracked.
  • 19.
    Attaching an ExistingEntity to the ContextEntity that already exists in the database but which is not currently being tracked by the context then you can tell the context to track the entity using the Attach method on DbSet.
  • 20.
  • 21.
    Marking a Propertyas ModifiedMarking a property as modified forces an update to be send to the database for the property when SaveChanges is called even if the current value of the property is the same as its original value.
  • 23.
    Current values: PropertyId has value 1 Property Name has value FrankyProperty Version has value System.Byte[] Property PrincessId has value 1 Original values: Property Id has value 1 Property Name has value BinkyProperty Version has value System.Byte[] Property PrincessId has value 1 Database values: Property Id has value 1 Property Name has value Squeaky Property Version has value System.Byte[] Property PrincessId has value 1
  • 24.
    Setting Values FromAnother ObjectCurrent values: Property Id has value 1 Property Name has value Rapunzel Original values: Property Id has value 1 Property Name has value Rosannella
  • 25.
    Getting & SettingComplex Pro’s
  • 26.
    Dynamic ProxiesWhen creatinginstances of POCO entity types, the EF often creates instances of a dynamically generated derived type that acts as a proxy for the entity. This proxy overrides some virtual properties of the entity to insert hooks for performing actions automatically when the property is accessed.Configuration.ProxyCreationEnabled = true;
  • 27.
    Creating an Instanceof a ProxyThe Create method does not add or attach the created entity to the context.If the entity type is sealed and/or has no virtual properties then Create will just create an instance of the entity type.
  • 28.
    Automatically Detecting ChangesDbContextautomatically detecting changes when the following methods are called:DbSet.FindDbSet.LocalDbSet.RemoveDbSet.AddDbSet.AttachDbContext.SaveChangesDbContext.GetValidationErrorsDbContext.EntryDbChangeTracker.Entries
  • 29.
    Disabling Auto DetectingChangesperformance improvementsAn alternative to disabling and re-enabling is to leave automatic detection of changes turned off at all times and either call context.ChangeTracker.DetectChangesexplicitly.