EF使用fluent api创建可选关系
本文关键字:关系 创建 api 使用 fluent EF | 更新日期: 2023-09-27 18:08:17
这些是我的类:
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; }
}
现在在Department中Manager是可选的。我如何使用流利的api建立这种关系?我想我需要使用modelBuilder.Entity<Department>().HasOptional(e => e.Manager)
,但不知道下一步该怎么做。我做错了什么?
更新:我已经为我的部门准备了这段代码,如果有什么不同的话:
modelBuilder.Entity<Department>()
.HasMany(e => e.ChildDepartments)
.WithOptional(e => e.ParentDepartment)
.HasForeignKey(e => e.ParentDeptId);
你需要完成这个关系
modelBuilder.Entity<Department>().HasOptional(e => e.Manager).WithOptionalDependent();