E.g。我有2个实体:
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
之间创建第二个关联吗? Don'想要将Managers存储在另一个表中,以便它们也存储在Employee表中,并且位于Position
字段“Manager”中。
答案 0 :(得分:1)
定义关系如下。
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; }
}