简体   繁体   English

如何在Entity Framework中通过Fluent API设置层次结构

[英]How to set up a hierarchy via Fluent API in Entity Framework

I have a hierarchy of employees, which have boss and subordinates. 我有一个员工层次结构,其中有老板和下属。

public class Employee
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Job { get; set; }
    public virtual Employee Boss { get; set; }
    public virtual ICollection<Employee> Subordinates { get; set; }
}

I tried to configure it as follows: 我尝试将其配置如下:

internal class EmployeeConfiguracao : EntityTypeConfiguration<Employee>
{
  public EmployeeConfiguracao()
  {
    HasOptional(p => p.Boss).WithMany(p => p.Subordinates).WillCascadeOnDelete(false);
  }
}

But the result of Add-Migration Init 但是Add-Migration Init的结果
Note that Boss is not-null but the is optional (president has no boss) 请注意,老板不是空的,但老板是可选的(总统没有老板)

CreateTable(
    "dbo.Employees",
    c => new
        {
            Id = c.Int(nullable: false, identity: true),
            Name = c.String(nullable: false, maxLength: 90),
            Job = c.String(),
            Boss_Id = c.Int(),
        })
    .PrimaryKey(t => t.Id)
    .ForeignKey("dbo.Employees", t => t.Boss_Id)
    .Index(t => t.Boss_Id);

How to set up this hierarchy so that it can be employed without boss (as President) 如何建立这种等级制度,以便在没有老板的情况下就可以使用(作为总裁)

If Boss should be nullable it should be defined like this: 如果Boss应该可以为空,则应该这样定义:

Boss_Id = c.Int(nullable: false)

If it is setup like this: 如果是这样设置的:

Boss_Id = c.Int()

then default value for nullable will be used which is true, so it is as you wanted it to be. 那么将使用nullable的默认值true,因此它就是您想要的默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM