ObjectStateManager vs Entry().State

entity-framework entity-framework-4 entity-framework-6

Question

What is the difference between this two and which is preferred? using change object state or Entry().state

db.ObjectStateManager.ChangeObjectState(employeeFromDB, EntityState.Modified)

vs

context.Entry(employeeFromDB).State = EnitityState.Modified;
1
2
10/7/2014 4:30:06 AM

Accepted Answer

Basically, you are invoking a function on the underlying System.Data.Objects.ObjectStateManager of your DbContext class to change a Property vs retrieving and changing it directly via the DbContext.

In the first example ChangeObjectState() can only be used to modify an ObjectStateEntry of an entity that already exists within the context. If you try to modify something that doesn't exist you'll get an exception thrown.

Check Exceptions in ObjectStateManager.ChangeObjectState

In the second example if the object doesn't exist in the context it gets added, you'll still get an exception when you call db.saveChanges() but the same approach could be used to add a new record just by changing EntityState.Modified to EntityState.Added

You'll also need to grab the underlying ObjectContext from your DbContext using ((IObjectContextAdapter)context).ObjectContext

3
1/11/2017 9:01:35 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow