繁体   English   中英

自引用实体和插入顺序-首先使用实体​​框架代码

[英]Self referencing entity & insert order - using Entity Framework Code First

我有两个看起来像这样的实体:

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现在尝试首先插入引用不存在的AssetK到AssetSession上的Asset,因此出现以下错误的原因:

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和外键问题

总结Slauma的答案,我正在清除EF插入之前的垂直导航值。 尽管这是一个不同的问题,但可能会有所帮助,这引起了一个问题。

潜在解决方案

如果您将所有AssetSession对象都放置到Asset对象中,然后执行一个root添加,则应该允许EF正确插入两者。

注意:为此,您可能需要在插入对象之前生成GUID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM