2017-05-26 20 views
1

我有很多一對多的關係人,將模型:EF自多到許多額外的參數

例如:

public Person() 
{ 
    ICollection<Person> Management {get;set;} 
    ICollection<Person> Staff {get;set;} 
} 

每個經理可能有許多相關人員,每個工人可能有許多相關的經理。

所以我也有一個連接表:

public class PersonLinks 
{ 
    public int ManagerId { get; set; } 

    public int StaffId { get; set; } 

    public MyTypeEnum/or maybe int/ RelationshipType { get;set; } 
} 

還精通API代碼:

modelBuilder.Entity<Person>().HasMany(m => m.Staff).WithMany().Map(m => 
{ 
    m.MapLeftKey("StaffId"); 
    m.MapRightKey("ManagerId"); 
    m.ToTable("PersonLinks"); 
}); 

modelBuilder.Entity<Person>().HasMany(m => m.Management).WithMany().Map(m => 
{ 
    m.MapLeftKey("ManagerId"); 
    m.MapRightKey("StaffId"); 
    m.ToTable("PersonLinks"); 
}); 

這個效果很好,但我想也映射「MyTypeEnum關係」屬性的Person模型,所以我可以這樣做:

myPerson.Management.Add(new Person{RelationshipType = ...}) 

或者:

myPerson.Staff.FirstOrDefault().RelationshipType = ... 
+0

要做到這一點找你e需要映射路口表 – octavioccl

回答

2

當你在聯接表的其他列,你需要把它映射爲模型的一部分,並創建兩個一對多的關係:

// Configure the primary key for the PersonLinks 
modelBuilder.Entity<PersonLinks>() 
    .HasKey(t => new{t.ManagerId,t.StaffId }); 

modelBuilder.Entity<PersonLinks>() 
    .HasRequired() 
    .WithMany(t => t.Management) 
    .HasForeignKey(d => d.ManagerId); 

modelBuilder.Entity<PersonLinks>() 
    .HasRequired() 
    .WithMany(t => t.Staff) 
    .HasForeignKey(d => d.StaffId); 

和你的個人實體將成爲

public Person() 
{ 
    // other properties 
    ICollection<PersonLinks> Management {get;set;} 
    ICollection<PersonLinks> Staff {get;set;} 
} 

現在,您可以將其添加爲你正在嘗試做的:

myPerson.Management.Add(new PersonLinks{RelationshipType = ...}); 
+0

沒問題,但我想避免在模型中使用ICollection 屬性,並且只能與人員一起工作。 – Xavr

+1

我恐怕沒有另一種方式:( – octavioccl