【问题标题】:Optional One to many Relationship using entity framework (fluent Api)使用实体框架(流利的 Api)的可选一对多关系
【发布时间】:2018-09-10 14:32:38
【问题描述】:

我们可以在实体框架中有可选的一对多关系

看看下面的Department和Person类

public class Person
{
    public int Id{ get; set; }

    public Department Department { get; set; }
    public int DepartmentId
}

public class Department
{
    public int Id{ get; set; }

    public List<Person> Members { get; set; }
}

Person to Department
.HasOptional(m => m.Department)
.WithOptional( d => d.Members)
.HasForeignKey( m=> m.DepartmentId);

结果应该是这样的。

Id 名称部门Id

1 约翰 x

2 艾哈迈德 y

3 个人 NULL

4 个人 x

从上面的例子可以看出,有些人有部门,有些人没有 该部门有一份人员名单。

现在这给了我一个错误。像这样

Multiplicity 与 Role 中的引用约束冲突 由于 Dependent Role 中的所有属性都不可为空,因此 Principal Role 的复数必须为“1”。

【问题讨论】:

    标签: entity-framework entity ef-fluent-api


    【解决方案1】:

    问题是您的型号和配置不匹配。在 fluent API 中,您将依赖项的外键配置为可选,但在您的模型中,外键是必需的:

    在您的Person 班级更改中:

    public int DepartmentId
    

    public int? DepartmentId
    

    这样可以确保外键实际上可以在数据库中具有值“NULL”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-13
      • 2015-06-01
      • 2014-05-25
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 2012-02-14
      • 2017-06-27
      相关资源
      最近更新 更多