Entity Framework Object Context

来源:互联网 发布:编程语言实现模式 代码 编辑:程序博客网 时间:2024/05/22 17:39

From Entity Framework 4 In Action

Entity Framework Object Context In Depth

                Theentity lifecycle

                                -Added—The entity is marked as added.

                                -Deleted—Theentity is marked as deleted.

                                -Modified—The entity has been modified.

                                -Unchanged—The entity hasn’t been modified.

                                -Detached—The entity isn’t tracked.

 

the context holds the state of an entity and maintainsmodifications made to the properties of the entity. This feature is known aschange tracking (or object tracking).If you create an entity outside thecontext, its status is Detached because the context can’t track it.

 

**the state indicates the relationship between the entityand the context, and not the entity and the database.Naturally, the state of anentity affects the way it’s persisted. Not surprisingly, when you persistentities, those in the Added, Modified, or Deleted state are saved using theINSERT, UPDATE, or DELETE command in the database.

 

                Managingentity state

                                -AddObject—Addsan entity to the context in the Added state

                                -Attach—Attachesan entity to the context in the Unchanged state

                                                **Becausean attached entity goes to the Unchanged state, you must find a way to mark itas Modified to persist it in the database. The next methods we’ll discuss cando this.

                                -ApplyCurrentValuesand ApplyOriginalValues—Change the state to Modified, comparing the trackedentity with another one

                                                **TheApplyOriginalValues method takes an entity as input (the one coming from thedatabase, in this case).the method copies the values of the input entity’sscalar properties into the original value of the context entity’s scalarproperties. At this point, the scalar properties’ original values held in thecontext contain data from the database, whereas the scalar properties’ currentvalues held in the context contain the values of the entity from the webservice. If original values are different from current values, the entity isset to Modified state; otherwise it remains Unchanged.

                                                **ApplyCurrentValues:Insteadof attaching the entity and querying the database, you can query the databaseand then apply modifications from the web service’s entity.It takes an entityas input (the one from the web service, in this case).the method copies thevalues of the input entity’s scalar properties into the current value of the contextentity’s scalar properties. At this point, the current values held in thecontext contain data from the web service entity, and the original values arethe values from the database. If they are different, the entity is set toModified state; otherwise it remains Unchanged.

                                -DeleteObject—Marksan entity as Deleted

                                -AcceptAllChanges—Marksall entities as Unchanged

                                -ChangeStateand ChangeObjectState—Change an entity from one state to another without anyrestrictions (except for Detached)

                                -Detach—Removesan entity from the context

                **Thesemethods are exposed by the ObjectContext and ObjectSet<T> classes

                **ChangeStateis exposed by the ObjectStateEntry class, whereas ChangeObjectState is exposedby the ObjectStateManager class

                                osm.ChangeObjectState(entity,EntityState.Unchanged);

                                osm.GetObjectStateEntry(entity).ChangeState(EntityState.Unchanged);

                               

                Managingchange tracking with ObjectStateManager

                                -BecauseObjectContext wraps the state manager, it’s still valid to say that the contextperforms the tracking.

                                -varosm = ctx.ObjectStateManager;

                                **Technicallyspeaking, the state manager can’t monitor modifications to properties inside anentity; it’s the entity that notifies the state manager when a change is made.

                                -DetectChanges():whichis internally invoked by the SaveChanges method

                                -Modifyingentity state from the entry (ObjectStateEntry)

                                                -Delete

                                                -SetModified:Marksthe entity and all of its properties as Modified. This method is internallyinvoked by ChangeState when moving to the Modified state.

                                                -SetModifiedProperty:Marksa property as Modified, and consequently marks the entity too.

                                                -AcceptChanges:Changesthe entity’s state to Unchanged and overrides the original values of the entrywith the current ones.

                                                -ChangeState

                               

                Changetracking and MergeOption

                                -MergeOptionis a property of the ObjectSet<T> class

                                                -AppendOnly(AppendOnly is the default merge option.)

                                                                :newentities retrieved by the query are attached to the ObjectContext, and if anentity which has the same key as an incoming entity is already attached to thecontext, then that object is returned as is rather than the incomingentity. 

                                                -OverwriteChanges

                                                                :If an object is already in the context, the current and original values ofobject's properties in the entry are overwritten with data source values. Thestate of the object's entry is set to Unchanged,

                                                -PreserveChanges

                                                                :Inthe .NET Framework version 4, the Entity Framework compares the current valuesof unmodified properties with the values that were returned from the datasource. If the values are not the same, the property is marked as modified.

                                                -NoTracking:justgive me whatever entities come from the database without trying to attach oridentity resolve them against the context

 

                Handlingconcurrency in Entity Framework

                                -Enablingoptimistic concurrency checking

                                                -Changeproperty of table Concurrency Mode to "Fixed"

                                -CatchCurrency

                                                -try

                                                                {

                                                                ...

                                                                ctx.SaveChanges();

                                                                }

                                                                catch(OptimisticConcurrencyException ex)

                                                                {

                                                                Log.WriteError(ex.StateEntries,ex.InnerException);

                                                                }

                                                                catch(UpdateException ex)

                                                                {

                                                                //Somelogic

                                                                }

                                -Managingconcurrency exceptions

                                                -ObjectContextclass’s Refresh method:ClientWins and StoreWins

                                                -try

                                                                {

                                                                ctx.SaveChanges();

                                                                }

                                                                catch(OptimisticConcurrencyException ex)

                                                                {

                                                                varerrorEntry = ex.StateEntries.First();

                                                                ctx.Refresh(RefreshMode.ClientWins,errorEntry.Entity);

                                                                ...

                                                                }

                                                **Ifyou invoke SaveChanges after Refresh, the database is updated without confilct

                Managingtransactions

                                -using(var transaction = new TransactionScope())

                                                {

                                                ...

                                                scope.Complete();

                                                }


原创粉丝点击