我有两个如下所示的实体:
public class AssetSession
{
[Key]
public Guid Id { get; set; }
public string RoomNumber { get; set; }
public Contact Contact { get; set; }
public virtual List<Asset> Assets { get; set; }
}
public class Asset
{
[Key]
public Guid Id { get; set; }
public Guid? ParentId { get; set; }
[ForeignKey("ParentId")]
public Asset Parent { get; set; }
public string Barcode { get; set; }
public string SerialNumber { get; set; }
public Guid AssetSessionId { get; set; }
[ForeignKey("AssetSessionId")]
public AssetSession AssetSession { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Asset>()
.HasOptional(t => t.Parent)
.WithMany()
.HasForeignKey(t => t.ParentId);
}
AssetSession 与 Asset 具有一对多关系。一切都运行良好,直到最近我在 Asset 上引入了自引用实体(称为 Parent)。
我的问题是,在插入新的 AssetSession 记录时进行一些 SQL 分析后,EF 现在似乎尝试首先插入引用 AssetSession 上不存在的 FK 的资产,因此我收到以下错误:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Assets_dbo.AssetSessions_AssetSessionId"
该错误是不言自明的,但我不明白的是为什么 INSERT 语句的顺序不是首先创建 AssetSession 以便 Assets 引用正确的 AssetSession。
我的插入代码如下所示:
using (var context = new AssetContext())
{
var assetSession = jsonObject; // jsonObject being passed into the method
var existingSession = context.AssetSessions.FirstOrDefault(c => c.Id == assetSession.Id);
if (existingSession == null)
{
var existingContact = context.Contacts.FirstOrDefault(c => c.Id == assetSession.Contact.Id);
if (existingContact != null)
{
context.Contacts.Attach(existingContact);
assetSession.Contact = existingContact;
}
context.Entry(assetSession).State = EntityState.Added;
context.SaveChanges();
}
}
我在使用 EF 的外键时遇到了同样的错误。它可能不相关,但是提供的答案帮助我理解了为什么我收到错误。
EF 和外键问题 https://stackoverflow.com/questions/21869330/entity-framework-inserting-child-objects-in-the-wrong-order/21894251?noredirect=1#21894251
总结 Slauma 的回答,我在 EF 插入之前清除了垂直导航值。这引起了一个问题,尽管这是一个不同的问题,但它可能会有所帮助。
潜在的解决方案
如果您将所有 AssetSession 对象添加到 Asset 对象中,然后执行一个根添加,这应该允许 EF 正确插入两者。
注意:为此,您可能需要在插入对象之前生成 GUID。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)