我可以在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.Employees
与Employee.Id
相关联(正如我已经做过的那样:((并且相反:Employee.Department
与Department.Id
(。
问题:
1( 这是一个还是两个关联?
2( 我可以在Department.Manager
和Employee.Id
之间创建第二个关联吗?不想将经理存储在另一个表中,因此他们也存储在Employee表中,并且在Position
字段中有"经理"。
如下定义关系。
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; }
}