Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 225
myfinite Avatar asked Feb 01 '26 15:02

myfinite


1 Answers

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

like image 188
Sirhc Avatar answered Feb 03 '26 11:02

Sirhc