【发布时间】:2015-05-20 11:46:26
【问题描述】:
我有这样的模型:
public class EntityFirst
{
public int Id { get; set; }
public int EntityThirdId { get; set; }
public virtual EntityThird { get; set; }
}
public class EntitySecond
{
public int Id { get; set; }
public int EntityThirdId { get; set; }
public virtual EntityThird { get; set; }
}
public class EntityThird
{
public int Id { get; set; }
// These columns are unique together
public int DocumentType { get; set; }
public string DocumentNumber { get; set; }
}
假设我必须将 EntityFirst 和 EntitySecond 对象插入数据库。但是EntityThird 有一些独特性,DocumentType 和DocumentNumber 在一起是独特的。所以,在调用SaveChanges 之前,我正在检查数据库中是否存在这样的EntityThird。如果它存在,那么我将其设置为Id 并设置为父级的EntityThirdId,当然还要将此实体的状态更改为Detached。
到目前为止,一切都很好。
问题是:
如果EntityFirst 和EntitySecond 具有EntityThird 对象,它们都具有相同的DocumentType 和DocumentNumber 会怎样。在这种情况下,我必须只将其中一个插入数据库并获取新插入的对象Id。然后将两个实体中的EntityThirdId 值设置为此Id。
我该如何解决这个问题?
【问题讨论】:
标签: c# .net entity-framework entity-framework-5