Search code examples
entity-frameworkentity-framework-4entity-framework-6

ObjectStateManager vs Entry().State


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;

Solution

  • 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