Save detached entity in Entity Framework 6

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...
    context.SaveChanges();
}

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;
}

Leave a Comment