自我参照实体插入订单 - 首先使用实体​​框架代码 [英] Self referencing entity & insert order - using Entity Framework Code First

查看:135
本文介绍了自我参照实体插入订单 - 首先使用实体​​框架代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two entities looking like this:

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具有多对多关系。一直运行良好,直到最近我引用了资源(称为父)的自引用实体。

AssetSession having a to-many relationship with Asset. Everything worked fine until recently when I introduced the self referencing entity on Asset (called Parent).

我的问题是,在插入新的AssetSession记录后的一些SQL分析之后,似乎EF现在尝试首先在AssetSession上插入资产引用不存在的FK,因此我收到以下错误的原因:

My problem is that after some SQL profiling when inserting new AssetSession records it seems that EF now tries to first insert the Asset referencing a non-existing FK on AssetSession hence the reason why I get the following error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Assets_dbo.AssetSessions_AssetSessionId"

错误很漂亮-explanatory但是我没有得到的是为什么INSERT语句的顺序不是首先创建AssetSession,以使资产引用正确的AssetSession才能开始。

The error is pretty self-explanatory but what I don't get is why the order of the INSERT statement does not start by creating the AssetSession first in order for Assets to reference the correct AssetSession.

我的代码插入如下所示:

My code for inserting looks like this:

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的外键有相同的错误。这可能不是相关的,但提供的答案有助于我了解为什么我收到错误。

I have had the same error with foreign keys using EF. It may not be related however the answer that was provided helped me understand why I was getting the error.

有EF和外键的问题

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

In summary of Slauma's answer I was clearing the vertical navigation values before my EF insert. This caused an issue, all-though it is a different issue it may help.

潜在解决方案

如果您的AssetSession对象位于您的Asset对象,然后执行一个根添加,应允许EF正确插入。

If you where to all your AssetSession object to your Asset object and then do one root add that should allow EF to insert both correctly.

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

Note: To do this you may need to generate your GUID in advance of inserting your objects.

这篇关于自我参照实体插入订单 - 首先使用实体​​框架代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆