我有 2 个表:
网站:
public class Site
{
public int Id { get; set; }
public virtual PersonDetail Person { get; set; }
}
人物详情:
public class PersonDetail
{
public int Id { get; set; }
public virtual Site PbnSite { get; set; }
}
一个网站不一定有一个人,一个人也不一定有一个网站。因此,这种关系在两端都是可选的。 我收到错误:
Unable to determine the principal end of an association between the types 'Site' and 'PersonDetail'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
尝试使用此架构更新我的数据库时。 我知道一个解决方案是根据需要设置其中一个,但鉴于它们都不是必需的,我自然会假设有一种方法可以创建可选关系。
最佳答案
在一对一关系中,一端必须是主体,第二端必须是从属。重写 Context 类中的 OnModelCreating
方法并试试这个:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PersonDetail>()
.HasOptional(p => p.PbnSite)
.WithOptionalPrincipal(s => s.Person);
}
关于c# - 两个实体之间的可选关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198223/