我正在使用 Entity 更新数据库中的一行。我的表单返回一个对象,该对象应该更新存储在数据库中的旧对象。当我发现用户将密码字段留空时,我想保留旧对象的相同旧密码值。每当我调用数据库询问旧对象时,我都会在使用 Entity 更新对象时遇到错误。我已经尝试了所有的 AddOrUpdate、Attach、Detach 东西,但没有任何效果。另外,我不能先删除再添加,因为 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();
}
实体框架跟踪您已加载的对象。因此,当您查询数据库中的OldConnector
对象时,该项目将保存在内存中。
然后继续尝试保存NewConnector
具有相同主键 ID 的对象。实体框架检查其内部状态并找到匹配的实体,这就是您收到错误的原因。由于您正在尝试更新现有对象,因此您应该这样做:
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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句