How to detect if an Entity Framework Object has changed?

How to detect if an Entity Framework Object has changed?

My code basically loads in the object from the DB and applies values to some properties (however they may be the same as the original). I know I can check entityObject.EntityState, but does it update if children have a change, or do I need to loop through all the children in the object?

Is the code to update only modified fields good?

I’m working on a website on ASP.NET MVC4 and EF5. I want to ensure that only modified values are updated in the database. I’m using a unit of work pattern and repositories for data work. Here’s the code for a generic repository. I’ve two questions, and need a code review for the following code. Is the code to update only modified fields good?

When do you call savechanges do you worry about concurrent users?

I am just learning EF but I would worry about concurrent users with your update. When you call SaveChanges it would be best if EF will only update the fields that are changed to minimize the chance for collisions or overwriting the changes of a concurrent user. Thanks for contributing an answer to Code Review Stack Exchange!

How to use ismodified field of each property accessible by context?

Use IsModified field of each property accessible by Context.Entry (Entity).Properties. In this example the modified entries are listed as a Tuple of the original an current value, indexed by name.

What happens when entity is marked for update?

The Update method normally marks the entity for update, not insert. However, if the entity has an auto-generated key, and no key value has been set, then the entity is instead automatically marked for insert.

What happens when savechanges is called on an entity?

Note that no changes will be made to the database if SaveChanges is called without doing any other manipulation of the attached entity. This is because the entity is in the Unchanged state. Another way to attach an existing entity to the context is to change its state to Unchanged.

What happens when you change the state of an entity?

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.