【发布时间】:2017-05-26 13:55:36
【问题描述】:
我有一个与 Person 具有多对多关系的 Person 模型:
例如:
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; }
}
还有 Fluent 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 = ...
【问题讨论】:
-
为此,您需要映射联结表
标签: c# entity-framework ef-code-first