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

code-first entity-framework


The ObjectContext class, which is mentioned in every sample I've seen, doesn't seem to exist in CTP5. I should emphasize that CTP5 is my first exposure to the Entity Framework at this time.

My DbContext is tied to a disconnected POCO that I have created. However, SaveChanges does not recognize the modification; how can I instruct my context to update that entity?

// The user has been replaced.
// The change is not saved.

Why am I misusing this?

The 12/01/2011 update Most people probably wouldn't find that surprising, however when I first started using EF, I didn't realize that adding an object that was previously connected would reverse the prior state. I was quite hurt by this. The object may have previously been associated or could have been generated from scratch as a consequence of ASP.NET MVC binding, but I wanted to utilize the Repository pattern in a very general approach that didn't care in either case. I therefore need anUpdateUser I've posted it below as a technique.

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

The procedure, which is called, plainly expects that the object existing in the data storage in some way.UpdateUser at any rate. If the item is already associated, you will have access to its prior state, enabling an optimized update to the database. If the item wasn't connected, the process would make the whole thing unclean.

Now that it is evident, it wasn't before. Hope it may be of some use.


6/15/2011 3:38:00 PM

Accepted Answer

An entity enters a Unchanged state when you Attach it (it has not been changed since it attached to the context). The Entity State just has to be changed explicitly to Modified.

_context.Entry(user).State = System.Data.Entity.EntityState.Modified;
5/7/2014 5:28:00 AM

Popular Answer

Casting the DbContext to IObjectContextAdapter will allow you to access the ObjectContext, just to be sure.

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

But I'm going to go with Morteza's approach since it's more cleaner.

Related Questions


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