强制EF 4.1代码优先以查看附加实体是否已修改 [英] Force EF 4.1 Code First to See an Attached entity as Modified

查看:60
本文介绍了强制EF 4.1代码优先以查看附加实体是否已修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的所有示例均涉及一个名为ObjectContext的类,该类似乎在CTP5中不存在。在这一点上,我必须强调,CTP5是我第一次接触实体框架。

All the examples I've found refer to a class called ObjectContext, which doesn't appear to exist in CTP5. I must stress at this point, CTP5 is my first exposure to the Entity Framework.

我已将断开连接的POCO附加到DbContext上。但是,SaveChanges不会获取更改,我如何告诉上下文更新该实体?

I have a disconnected POCO that I have attached to my DbContext. SaveChanges does not pick up the change though, how I tell my context to update that entity?

_context.Users.Attach(user);
// The user has been replaced.
_context.SaveChanges();
// The change is not saved.

我在做什么错了?

2011年12月1日更新
对于大多数人来说可能是显而易见的,但是作为EF的首次用户,我没有想到附加一个已经附加的对象会清除以前的状态。这让我很痛苦。但是我想以一种非常通用的方式使用存储库模式,这种方式并不关心对象是否已附加或由于ASP.NET MVC绑定而被重新创建。所以我需要一个 UpdateUser 方法,并将它附加在下面。

Update 12/01/2011 Might be obvious to most, but as a first time user of EF, it didn't occur to me that attaching an object that was already attached would clear the previous state. This caused me a lot of pain. But I wanted to use the Repository pattern in a very generic way, a way which didn't care if the object was already attached or had been freshly created as the result of ASP.NET MVC binding. So I needed an UpdateUser method, and I've attached it below.

    public User UpdateUser(User user) {
        if (_context.Entry(user).State == EntityState.Detached) {
            _context.Users.Attach(user);
            _context.Entry(user).State = EntityState.Modified;
        }
        return user;
    }

该方法显然假定对象以某种方式存在于数据存储中,毕竟它叫做 UpdateUser 。如果对象已被附加,则您将从对象的先前状态中受益,从而可以对数据库进行优化更新。但是,如果未附加对象,则该方法将使整个对象变脏。

The method obviously assumes that the object exists in the data store in some fashion, it's called UpdateUser after all. If the object is already attached, you will benefit from the object's previous state, which in turn will allow for an optimised update to the DB. However, if the object was not attached, the method forces the whole thing to become dirty.

现在似乎很明显,以前是没有的。希望它能对某人有所帮助。

Seems obvious now, wasn't before. Hope it helps someone.

丰富

推荐答案

>附加实体,它会变为未更改状态(自从附加到上下文以来就没有更改)。您需要做的就是将实体状态显式更改为 Modified

When you Attach an entity, it goes to Unchanged state (it has not been changed since it attached to the context). All you need to is to explicitly change the Entity State to Modified:

_context.Users.Attach(user);
_context.Entry(user).State = System.Data.Entity.EntityState.Modified;
_context.SaveChanges();

这篇关于强制EF 4.1代码优先以查看附加实体是否已修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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