【问题标题】:EF Self many-to-many with additional parametersEF Self 多对多,带附加参数
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 没关系,但我想避免模型中的 ICollection 属性,只与人员一起使用。
  • 恐怕没有别的办法了 :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多