4

I have an entity (TerminalCertification) which has relation to other entities. I want to make user to be able to update TerminalCertification but I'm not able to update related object which is updated by user. My update code is here:

public void UpdateTerminalCertification(TerminalCertification terminalCertification)
{
    var lastCertification = db.terminalCertifications.Find(terminalCertification.TerminalCertificationID);

    if (lastCertification==null)
        throw new TerminalCertificationNotFoundException(terminalCertification)                                   
        db.Entry(lastCertification).CurrentValues.SetValues(terminalCertification);
    }

I have searched stackoverflow and found below code but there is not such ObjectStateManager in DBContext class.

ObjectStateManager stateMgr = db.ObjectStateManager;    
ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model);
stateEntry.SetModified();

what should I do?

Mark Bell
  • 28,985
  • 26
  • 118
  • 145
JGC
  • 12,737
  • 9
  • 35
  • 57

2 Answers2

4

You can cast your DbContext to an IObjectContextAdapter which has the underlying ObjectContext and then use the ObjectStateManager off of that.

Jeff
  • 35,755
  • 15
  • 108
  • 220
  • it throws this error:The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type ... – JGC Jul 11 '11 at 20:49
  • Attach the entity to the DbContext first. – Jeff Jul 11 '11 at 20:52
  • how to attach my object to DBContext? – JGC Jul 14 '11 at 13:25
  • http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx – Jeff Jul 14 '11 at 13:54
  • also, you can read about it here : http://thedatafarm.com/blog/data-access/accessing-objectcontext-features-from-ef-4-1-dbcontext/ – Michael Mar 24 '12 at 16:36
0

Use the UpdateModel or TryUpdateModel method inside your controller. If you are doing it outside of the controller then this will not work.