Save detached entity in Entity Framework 6

c# entity-framework entity-framework-6

Question

Many posts about saving a detached entity in Entity Framework have been viewed by me. They all appear to be relevant to earlier iterations of Entity Framework. They make reference to functions that don't appear to exist, including ApplyCurrentValues and ChangeObjectState. I tried an approach I learned about through intellisense on a whim, but I want to make sure I'm doing it correctly because I can't see what's going on in the background:

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

Is this the proper approach to edit a previously published item that has been modified?

1
54
12/8/2013 8:45:53 AM

Accepted Answer

This is true, of course. This article outlines numerous techniques for attaching and adding entities. gives the following 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();
}

EF will update all of the following attributes since it is unable to determine which of them differ from those in the database:

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.

You can choose which attributes to change manually to prevent this, as opposed to changing the entity's state entirely:

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;
}
89
12/8/2013 8:31:19 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow