我可以在实体框架5中的两个实体之间创建多个关联,c#?

时间:2013-05-09 14:19:23

标签: c# database entity-framework entity-framework-5 entity-relationship

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.EmployeesEmployee.Id(和Employee.DepartmentDepartment.Id相关联)。

问题:
1)这是一个或两个协会吗?

2)我可以在Department.ManagerEmployee.Id之间创建第二个关联吗? Don'想要将Managers存储在另一个表中,以便它们也存储在Employee表中,并且位于Position字段“Manager”中。

1 个答案:

答案 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; }
}