gpt4 book ai didi

c# - 自引用实体和插入顺序 - 使用 Entity Framework Code First

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:53 25 4
gpt4 key购买 nike

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

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 的 Assets ,因此我收到以下错误的原因:

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 的外键方面遇到了同样的错误。它可能不相关,但是所提供的答案帮助我理解了为什么我会收到错误。

Issue with EF and Foreign keys

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

可能的解决方案

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

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

关于c# - 自引用实体和插入顺序 - 使用 Entity Framework Code First,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17483134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com