简体   繁体   中英

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
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_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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