To see an attached object as modified, force EF 4.1 code to run first.

code-first entity-framework

Question

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

1
21
6/15/2011 3:38:00 PM

Accepted Answer

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();
29
5/7/2014 5:28:00 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow