我可以在EntityFramework5,c#中创建两个实体之间的多个关联吗

本文关键字:实体 两个 之间 关联 EntityFramework5 创建 我可以 | 更新日期: 2023-09-27 18:12:46

例如,我有两个实体:

public class Department
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Employee> Employees { get; set; }
    public Employee Manager { get; set; }
}
public class Employee
{
    public Guid Id { get; set; }
    public string FullName { get; set; }
    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }
    public Guid DepartmentId { get; set; }
    public string Position { get; set; }
}

我知道我可以将Department.EmployeesEmployee.Id相关联(正如我已经做过的那样:((并且相反:Employee.DepartmentDepartment.Id(。

问题:
1( 这是一个还是两个关联?

2( 我可以在Department.ManagerEmployee.Id之间创建第二个关联吗?不想将经理存储在另一个表中,因此他们也存储在Employee表中,并且在Position字段中有"经理"。

我可以在EntityFramework5,c#中创建两个实体之间的多个关联吗

如下定义关系。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Department>()
        .HasRequired(a => a.Manager)
        .WithMany()
        .HasForeignKey(a => a.EmployeeId);
}

如果你想要懒惰的加载和更改跟踪,你也希望它们是虚拟的。

public class Department
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
    public virtual Employee Manager { get; set; }
}
相关文章: