Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is EntityState.Modified required for an update?

I've seen a lot of people when updating a record use:

...
ms.Status = status;
db.Entry(ms).State = EntityState.Modified;
db.SaveChanges();

Is this line required? I was able to do an update without it.

db.Entry(ms).State = EntityState.Modified;

I was wondering what this statement is actually used for if the context already knows it should update that record without you specifying it explicitly then why bother specifying it explicitly?

like image 800
John Avatar asked Mar 15 '12 10:03

John


People also ask

What is EntityState modified?

EntityState.Added : EntityState.Modified; context.SaveChanges(); } } Note that when you change the state to Modified all the properties of the entity will be marked as modified and all the property values will be sent to the database when SaveChanges is called.

What is EntityState in Entity Framework?

The Entity state represents the state of an entity. An entity is always in any one of the following states. Added: The entity is marked as added. Deleted: The entity is marked as deleted.


1 Answers

It is required if your changes in the entity was done when entity was not tracked by EF context (the entity was detached). If you load entity from the context, modify it and save it by the same context you don't need to use it because EF will track changes and set the state automatically.

like image 66
Ladislav Mrnka Avatar answered Oct 10 '22 22:10

Ladislav Mrnka