Force EF 4.1 Code First to See an Attached entity as Modified

后端 未结 3 1910
执念已碎
执念已碎 2020-12-29 05:08

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 Ent

相关标签:
3条回答
  • 2020-12-29 05:52

    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;
    }
    
    0 讨论(0)
  • 2020-12-29 06:03

    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.

    0 讨论(0)
  • 2020-12-29 06:05

    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();
    
    0 讨论(0)
提交回复
热议问题