Force EF 4.1 Code First to See an Attached entity

2019-02-03 01:17发布

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.

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.

What am I doing wrong?

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

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.

Rich

3条回答
萌系小妹纸
2楼-- · 2019-02-03 01:38

For the sake of completeness, you can access the ObjectContext by casting the DbContext to IObjectContextAdapter:

((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);

Morteza's method is much cleaner though and gets my vote.

查看更多
我命由我不由天
3楼-- · 2019-02-03 01:50

I believe u do not need to attach the entity before u call modified. simply setting to modified will do the job.

if (_context.Entry(user).State == EntityState.Detached)
{
    _context.Entry(user).State = EntityState.Modified;
}
查看更多
再贱就再见
4楼-- · 2019-02-03 01:54

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();
查看更多
登录 后发表回答