0

我写了一个更新方法,如下所示:

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;
    }
}

但是更新时出现以下错误:

一个实体对象不能被多个 IEntityChangeTracker 实例引用。

4

1 回答 1

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.

于 2013-06-29T19:35:49.743 回答