Save detached entity in Entity Framework 6

C#Entity FrameworkEntity Framework-6

C# Problem Overview


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.Orders.Attach(order);
        db.Entry(order).State = System.Data.Entity.EntityState.Modified;
        db.SaveChanges();
    }
}

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

C# Solutions


Solution 1 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKingOfHypocritesView Question on Stackoverflow
Solution 1 - C#Stephen JenningsView Answer on Stackoverflow