自参照实体放大器;为了插入 - 使用实体框架代码第一次 [英] Self referencing entity & insert order - using Entity Framework Code First

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

问题描述

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

 公共类AssetSession 
{
[重点]
公众的Guid标识{搞定;组; }
公共字符串RoomNumber {搞定;组; }
公共联络联系{搞定;组; }
公共虚拟目录<资产与GT;资产{搞定;组; }
}

公共类资产
{
[关键]
公众的Guid标识{搞定;组; }
公众的Guid? {的ParentId获得;组; }
[ForeignKey的(的ParentId)]
公共资产家长{搞定;组; }
公共字符串条码{搞定;组; }
公共字符串的SerialNumber {搞定;组; }
公众的Guid AssetSessionId {搞定;组; }
[ForeignKey的(AssetSessionId)]
公共AssetSession AssetSession {搞定;组; }
}

保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
{
modelBuilder.Entity<资产>()
.HasOptional(T => t.Parent)
.WithMany()
.HasForeignKey(T => t.ParentId);
}



具有资产一个一对多的关系AssetSession。一切正常,直到最近,当我介绍了自参考的资产(所谓的母公司)的实体。



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

  INSERT语句冲突与外键约束FK_dbo.Assets_dbo.AssetSessions_AssetSessionId

该错误是相当自我-explanatory但我不明白的是,为什么INSERT语句的顺序并不受为了资产以引用正确的AssetSession先创建AssetSession启动。



我插入看起来像这样的代码:

 使用(VAR上下文=新AssetContext())
{
VAR assetSession =的JSONObject; //被JSONObject的传递到方法

VAR existingSession = context.AssetSessions.FirstOrDefault(C => c.Id == assetSession.Id);

如果(existingSession == NULL)
{
VAR existingContact = context.Contacts.FirstOrDefault(C => c.Id == assetSession.Contact.Id);

如果(existingContact!= NULL)
{
context.Contacts.Attach(existingContact);
assetSession.Contact = existingContact;
}

context.Entry(assetSession).STATE = EntityState.Added;
context.SaveChanges();
}
}


解决方案

我曾与EF使用外键同样的错误。它可能不相关但被提供的帮助我了解为什么我得到错误的答案。



问题与EF键和外键



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



潜在的解决方案


$ ; b $ b

如果你在哪里你所有AssetSession对象的资产对象,然后做一个根补充说,应该允许EF正确插入两个



请注意:要做到这一点,你可能需要预先生成插入你的对象你的GUID。


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 having a to-many relationship with Asset. Everything worked fine until recently when I introduced the self referencing entity on Asset (called Parent).

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"

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

解决方案

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.

Issue with EF and Foreign keys

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.

Potential Solution

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.

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

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

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