EF使用流畅的api创建可选关系

时间:2014-06-12 17:44:15

标签: c# entity-framework fluent

这些是我的课程:

public class Department
{
    [Key]
    [Column("Department_Id")]
    public int DepartmentId { get; set; }

    [Required]
    [Column("Name")]
    public string Name { get; set; }

    [Column("Manager_Id")]
    public int? ManagerId { get; set; }

    [Column("Parent_Department_Id")]
    public int? ParentDeptId { get; set; }

    public virtual ICollection<Department> ChildDepartments { get; set; }

    public virtual Department ParentDepartment { get; set; }

    public virtual Employee Manager { get; set; }
}

public class Employee
{
    [Key]
    [Column("Employee_Id")]
    public int Id { get; set; }

    [Required]
    [Column("First_Name")]
    public string FirstName { get; set; }

    [Required]
    [Column("Last_Name")]
    public string LastName { get; set; }

    [Required]
    [Column("Job_Title_Id")]
    [ForeignKey("JobTitle")]
    public int? JobTitleId { get; set; }

    [Column("Manager_Id")]
    public int? ManagerId { get; set; }

    [Required]
    [Column("Department_Id")]
    public int? DepartmentId { get; set; }

    public virtual Department Department { get; set; }

    public virtual JobTitle JobTitle { get; set; }
}

现在在部门经理是可选的。如何使用流畅的api建立这种关系?我想我需要使用modelBuilder.Entity<Department>().HasOptional(e => e.Manager),但无法弄清楚接下来会发生什么。我做错了什么?

更新: 如果这有任何区别,我已经为我的部门提供了这段代码:

modelBuilder.Entity<Department>()
            .HasMany(e => e.ChildDepartments)
            .WithOptional(e => e.ParentDepartment)
            .HasForeignKey(e => e.ParentDeptId);

1 个答案:

答案 0 :(得分:0)

你需要完成那种关系

 modelBuilder.Entity<Department>().HasOptional(e => e.Manager).WithOptionalDependent();