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; } 
} 
相關問題