繁体   English   中英

EF Self多对多附加参数

[英]EF Self many-to-many with additional parameters

我有一个与人有多对多关系的人模型:

例如:

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 = ...

当联结表中还有其他列时,需要将其映射为模型的一部分,并创建两个一对多关系:

// 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 = ...});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM