EF Self with to many with many parameters

时间:2017-05-26 13:55:37

标签: c# entity-framework ef-code-first

我有一个与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; } 
}

也是流利的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 Relationship”属性映射到Person模型,所以我可以这样做:

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

或者:

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

1 个答案:

答案 0 :(得分: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 = ...});