在实体框架6中保存分离的实体

时间:2013-12-08 08:45:53

标签: c# entity-framework entity-framework-6

我已阅读很多关于在实体框架中保存分离实体的帖子。所有这些似乎都适用于旧版本的Entity Framework。它们引用了似乎不存在的ApplyCurrentValues和ChangeObjectState等方法。一时兴起,我决定尝试一种通过intellisense找到的方法,我想确保这是正确的方法,因为我无法看到幕后发生的事情:

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

这是更新已更改的现有项目的正确方法吗?

1 个答案:

答案 0 :(得分:87)

是的,这是正确的。 This article describes various ways of adding and attaching entities,它提供了这个示例:

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不知道哪些属性与数据库中的属性不同,因此它将全部更新:

  

当您将状态更改为Modified时,实体的所有属性都将被标记为已修改,并且在调用SaveChanges时,所有属性值都将发送到数据库。

为避免这种情况,您可以手动set which properties are modified而不是设置整个实体状态:

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