【问题标题】:Self referencing entity & insert order - using Entity Framework Code First自引用实体和插入顺序 - 首先使用实体​​框架代码
【发布时间】:2013-07-05 07:14:21
【问题描述】:

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

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();    
   }
}

【问题讨论】:

  • 首先,我认为有一个错字:if (existingSession != null)?其次,是否找到并附加了联系,或者是否在有联系和没有联系的情况下发生?三、哪些插入语句被发送到数据库?可能无意中在新的Asset 之上添加了现有的Asset(没有AssetSession)。

标签: c# entity-framework self-reference


【解决方案1】:

我在使用 EF 的外键时遇到了同样的错误。它可能不相关,但提供的答案帮助我理解了我收到错误的原因。

Issue with EF and Foreign keys

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

潜在解决方案

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2013-02-03
    相关资源
    最近更新 更多