TheHurt
TheHurt

Reputation: 1610

Why can I not update a record with dbContext?

I have tried to do my due diligence and read many of the questions here and I cannot solve my problem. I have a very simple pattern. I look up a record with a get method (with the appropriate where clause that gives me the record of interest):

public IQueryable<TDataModel> Get<TDataModel>() where TDataModel : class, IDataModel
{
   return _context.Set<TDataModel>();
}

Then I modify whatever properties of that object I am interested in, and then I pass the modified object to an update method:

public TDataModel Update<TDataModel>(TDataModel item) where TDataModel : class, IDataModel
{
    _context.Set<TDataModel>().Attach(item);
    _context.Entry<TDataModel>(item).State = EntityState.Modified;
    _context.SaveChanges();
    return item;
}

I am always blessed with the following:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

I have tried many of the solutions presented in many of the questions presented here to no avail.

Upvotes: 0

Views: 393

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67296

Because Entity Framework uses change tracking (by default...but you can switch it off using different MergeOptions), you cannot attach two entities with the same key (in the same context).

So, you either have to detach the old object first, or simple do not attach the new one (since the change tracker is already doing this job for you).

Upvotes: 1

Related Questions