在 Entity Framework 6 中保存分离的实体 [英] Save detached entity in Entity Framework 6

查看:31
本文介绍了在 Entity Framework 6 中保存分离的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

是的,这是正确的.本文介绍了各种添加和附加实体的方法,并提供了以下示例:

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

由于 EF 不知道哪些属性与数据库中的属性不同,它将全部更新:

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

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

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

这篇关于在 Entity Framework 6 中保存分离的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆