【发布时间】: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