【发布时间】:2020-08-06 17:47:20
【问题描述】:
更新:在我创建这篇文章之后,我没有看到导致插入失败的代码。现在一切都按预期工作。很抱歉,感谢您花时间提供帮助。
我遇到了一个问题,即 EF 尝试更新不存在的记录。我需要插入记录。
示例代码如下:
DoStuff(List<ParentObj> listParent, List<OtherParent> listOtherParent)
{
foreach(var op in otherParent)
{
var updateThisParentRecord = listParent.FirstOrDefault(x => x.Id == op.Id);
if(updateThisParentRecord != null)
{
updateThisParentRecord.ChildRecordList.Add(new ChildRecord
{
//set relevant props not PK as it is an identity column
OtherChildObject = new OtherChildObject
{
//set relevant props not PK as it is an identity column
}
});
}
}
await _parentObjectContext.SaveChangesAsync();
}
型号代码:
public partial class ParentObj
{
public ParentObj()
{
ChiledRecordList = new HashSet<ChildRecord>();
}
public int Id {get;set;}
public virtual ICollection<ChildRecord> ChildRecordList {get;set;}
}
public partial class ChildRecord
{
public int Id {get;set;}
public int ParentId {get;set;}
public int OtherChildObject {get;set;}
public virtual OtherChildObject OtherChildObject {get;set;}
public virtual ParentObj {get;set;}
}
public partial class OtherChildObject
{
public OtherChildObj()
{
ParentObj = new HashSet<ParentObj>();
ChildRecord = new Hashset<ChildRecord>();
}
public long Id {get;set;}
//now that I have written this out, the below line seems strange and may
//be keyed wrong?
public virtual ICollection<ParentObj> ParentObj {get;set;}
public virtual ICollection<ChildRecord> ChildRecord {get;set;}
}
保存时抛出以下异常:
"数据库操作预计会影响 1 行,但实际上会影响 0 行。 自加载实体以来,数据可能已被修改或删除。 有关理解和处理乐观并发异常的信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=527962。”
这是异常条目列表中的内容:{{Id: 1000} Modified EntityType: ChildRecord}
EF 生成的 SQL 正确地创建了 OtherChildObject,但它正在尝试更新不存在的 ChildRecord。有谁知道发生了什么?提前致谢
【问题讨论】:
-
人们会想看你的模型代码
-
已更新型号代码
-
你在“//设置相关道具而不是PK,因为它是一个身份列”部分中实际设置了什么?
-
我需要在此处添加更新。还有一些其他邪恶的代码从来没有线程通过它,它正在做一些愚蠢的事情,直到我意识到我一直跨过一个我认为之前已经被 QC 过的方法时我才注意到。
标签: c# .net-core entity-framework-core