0

I have written a update method, given below:

public CANDIDATE UpdateCandidateDetails(CANDIDATE objCandidate)
{
    using (var context = new URMSNEWEntities())
    {
        context.CANDIDATES.Attach(objCandidate);
        context.ObjectStateManager.ChangeObjectState(objCandidate, System.Data.EntityState.Modified);
        context.SaveChanges();
        return objCandidate;
    }
}

But when updating it is giving following error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Cœur
  • 37,241
  • 25
  • 195
  • 267
amitabha
  • 646
  • 1
  • 9
  • 20

1 Answers1

0

As Gert mentions in the comments that error is telling you that your object objCandidate, is already being tracked by another context.

You can't attach an already attached object, nor should you want to, as the two contexts are more than likely going to be in conflicting states.

In theory, you could Detach your object from the context to which it currently belongs, but that's likely to cause additional complications.

To track down where the object is attached (and the context to which it is attached), you'll have to look through your code to the place where your objCandidate was created (or attached), there will be another context that has been instantiated, from which you're obtaining the objCandidate object.

The best solution to the problem will likely involve sharing a common context throughout certain parts of your application.

Search this site for the UnitOfWork and Repository patterns for some excellent information/advice about how to manage your contexts. e.g. entity framework + repository + unit or work question

Good luck.

Community
  • 1
  • 1
Chris
  • 8,268
  • 3
  • 33
  • 46