0

例如我有2个实体:我可以在Entity Framework 5,c#中的两个实体之间创建多个关联吗?

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'想要将经理存储在另一个表中,因此他们也存储在Employee表中并且在Position字段“经理”中有。

+0

你可能想Manager从员工继承? – 2013-05-09 14:26:48

+0

@Sam Leach,谢谢你)不知道我是如何错过这个)但是我能否将经理存储在Employee表中? – 2013-05-09 14:29:07

+0

不,请参阅我的答案。只需将关系定义为一对一。 – 2013-05-09 14:42:39

回答

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; } 
} 
相关问题