保存独立实体,实体框架6 [英] Save detached entity in Entity Framework 6

查看:92
本文介绍了保存独立实体,实体框架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:

当您将状态更改为修改的所有实体的属性修改,所有的属性值将被发送到时调用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;
}

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

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