Save detached entity in Entity Framework 6


I've read through LOTS of posts on saving a detached entity in Entity Framework. All of them seem to apply to older versions of Entity Framework. They reference methods such as ApplyCurrentValues and ChangeObjectState which do not seem to exist. On a whim I decided to try a method I found through intellisense and I want to make sure this is the correct way to do this since I don't get to see what happening behind the scenes:

public void SaveOrder(Order order)
    using (VirtualWebEntities db = new VirtualWebEntities())
        db.Entry(order).State = System.Data.Entity.EntityState.Modified;

Is this the correct way to update an existing item that was changed?

Accepted Answer

Yes, this is correct. This article describes various ways of adding and attaching entities, and it provides this example:

var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" };
using (var context = new BloggingContext())
    // The next step implicitly attaches the entity
    context.Entry(existingBlog).State = EntityState.Modified;
    // Do some more work...

Since EF doesn't know which properties are different from those in the database, it will update them all:

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.

To avoid this, you can set which properties are modified manually rather than setting the entire entity state:

using (var context = new BloggingContext())
    var blog = context.Blogs.Find(1);
    context.Entry(blog).Property(u => u.Name).IsModified = true;     
    // Use a string for the property name
    context.Entry(blog).Property("Name").IsModified = true;

Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why