Updating existing data in EF 6 throws exception - “…entity of the same type already has the same primary key value.”

前端 未结 4 1705
眼角桃花
眼角桃花 2020-12-29 13:39

I am trying to update a record using Entity Framework 6, code-first, no fluent mapping or a tool like Automapper.

The entity(Employee) has other composi

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 14:09

    This worked for myself

    var aExists = _db.Model.Find(newOrOldOne.id);
    if(aExists==null)
    {
        _db.Model.Add(newOrOldOne);
    }
    else
    {
        _db.Entry(aExists).State = EntityState.Detached;
        _db.Entry(newOrOldOne).State = EntityState.Modified;
    }
    

提交回复
热议问题