When I update an element using this method, I get the ex开发者_JAVA百科ception:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
This is the method:
public void Set(TaskPrice entity)
{
bool isExists = GetQuery().Any(x => x.TaskId == entity.TaskId);
if (isExists)
{
ObjectStateEntry entry=null;
if (this.Context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry) == false)
{
this.ObjectSet.Attach(entity);
}
this.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
else
{
this.ObjectSet.AddObject(entity);
}
}
I undertand that this exception accurs because GetQuery().Any(x => x.TaskId == entity.TaskId);
attachs the element from db and when I attach the updated entity, it sais there is attached element with the same id.
Felipe Lima write in his article:
Always attach all your Entities before doing any operation/query in your ObjectContext. This way, you avoid any double-tracking request. If the ObjectContext needs your Entity later, it will retrieve the instance you attached before and you're good to go!
So your fixed code should be:
public void Set(TaskPrice entity)
{
ObjectStateEntry entry=null;
if (this.Context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry) == false)
{
this.ObjectSet.Attach(entity);
}
bool isExists = GetQuery().Any(x => x.TaskId == entity.TaskId);
if (isExists)
{
this.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
else
{
this.ObjectSet.AddObject(entity);
}
}
精彩评论