我有两个看起来像这样的实体:
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();    
   }
}