c# - 两个实体之间的可选关系

标签 c# entity-framework entity-framework-6

我有 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/

相关文章:

c# - 不满足前提条件时跳过事实/理论

c# - 没有 xaml 的 PropertyGrid(扩展 WPF 工具包)中的多行字符串?

entity-framework - DbContext.Entry 附加实体

c# - EF Core 搜索多列 null 错误

c# - Entity Framework Mysql 嵌套属性

c# - 文本框大小不随样式表改变

c# - 去掉 HTML 标签?

c# - 跟踪 Entity Framework 进度

c# - 在 Visual Studio 2013 中生成 .edmx EF6 的问题

c# - Entityframework RC1 - MetadataItem.Annotations made internal - 替代方案?