使用 3 列主键在多对多中加入 table

Join table in many-to-many with 3-column primary key

我想使用代码优先和流畅 API 基于 3 个实体创建 3 个 table。我正在使用 Entity Framework 版本 6。连接 table 需要一个 3 列主键和附加列。

我的问题:如何通过 C# Fluent API 使用代码优先来 create/map PatientTreatment table 的 3 列主键?谢谢。

连接的 3 列主键的详细信息 table { PatentId、TreatmentId、TreatmentDate }PatentIdTreatmentId 的值是从其他 2 个实体 (tables) 中获取的,而 TreatmentDate 的值是手动输入的(例如 C# 代码或 T-SQL 脚本喜欢调用 getdate() 函数)。

3 个实体的详细信息:

public class Patient {
  public long PatentId {get; set;} // database created using Identity
  ...
}

public class Treatment {
  public long TreatmentId {get; set;}  // database created using Identity
  ... 
}

并加入table(实体)

public class PatientTreatment
{
   public long PatentId {get; set;} // part of the primary key from the Patient entity
   public long TreatmentId {get; set;} // part of the primary key from the Treatment entity
   public DateTime TreatmentDate {get; set;} // part of the primary key but its value is from C# code or from T-SQL script, not from other entity (table)
   // other fields ...
}

我只是在 Whosebug 中搜索它

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships check this many to many with extra column

您不能将其建模为隐藏 PatientTreatment class 的多对多关联,这就是通常在 Entity Framework映射。

但您并不打算这样做,从您显示的明确 PatientTreatment class 中可以明显看出。所以这只是正确建模的问题。

OnModelCreating 替代 DbContext subclass 中,像这样设置映射:

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Entity<PatientTreatment>()
      .HasKey(x => new { x.PatientId, x.TreatmentId, x.TreatmentDate });
    mb.Entity<Patient>().HasMany(p => p.PatientTreatments)
      .WithRequired().HasForeignKey(x => x.PatientId);
    mb.Entity<Treatment>().HasMany(t => t.PatientTreatments)
      .WithRequired().HasForeignKey(x => x.TreatmentId);

    base.OnModelCreating(mb);
}

我认为这一行 HasKey(x => new { x.PatientId, x.TreatmentId, x.TreatmentDate }) 是您主要寻找的内容。