开发者

exception in set method

开发者 https://www.devze.com 2023-03-03 06:32 出处:网络
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 obje

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.

How can I solve this problem so the method will update?


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

精彩评论

暂无评论...
验证码 换一张
取 消