附加类型' ModelName"的实体失败,因为同一类型的另一个实体已具有相同的主键值

时间:2018-06-19 09:24:41

标签: c# .net entity-framework

我正在使用Entity更新数据库中的行。我的表单返回一个Object,它应该更新存储在DB中的旧对象。当我发现用户将密码字段留空时,我想保留旧对象的旧密码值。每当我调用数据库询问旧对象时,我都会在使用Entity更新对象时遇到错误。我已尝试过所有AddOrUpdate,Attach,Detach来自Entity的内容,但没有任何效果。此外,我无法删除然后添加,因为OldConnector在表上有一个我无法修改的增量ID。这是我的代码:

public void Update(Connector NewConnector)
    {
        {
            if (NewConnector.Password == "")
            {
                Connector OldConnector = _db.ConnectorsTable.Where(x => x.ID == NewConnector.ID).FirstOrDefault(); //Grabbing the old connectors password
                NewConnector.Password = OldConnector.Password;
            }
        }
        _db.Entry(NewConnector).State = EntityState.Modified; //Code Crashes here
        _db.SaveChanges();
    }

1 个答案:

答案 0 :(得分:1)

实体框架跟踪您已加载的对象。因此,当您在数据库中查询OldConnector对象时,该项目将保留在内存中。

然后,您继续尝试保存具有相同主键ID的NewConnector对象。实体框架检查它的内部状态并找到匹配的实体,这就是您收到错误的原因。由于您尝试更新现有对象,因此应该执行此操作:

public void Update(Connector newConnector)
{
    if (newConnector == null)
    {
        throw new ArgumentNullException(nameof(newConnector));
    }

    var oldConnector = _db.ConnectorsTable
        .Where(x => x.ID == newConnector.ID)
        .Single(); //Grabbing the old connectors password

    if (newConnector.Password == "")
    {
        newConnector.Password = oldConnector.Password;
    }

    //Update the old entity with values from the new entity:
    _db.Entry(oldConnector).CurrentValues.SetValues(newConnector);
    _db.SaveChanges();
}