实体框架没有主键的多对多关系

时间:2011-02-27 14:48:53

标签: entity-framework many-to-many

我有一些表,它们都是以多对多的关系相互引用,但不是正常的。

通常,多对多关系有一个连接表,它连接主键上的其他两个表。

在我的情况下,我有一些表通过共享匹配的外键相互关联。

我有两张桌子的病历。

  1. 分配给患者的医生。
  2. 患者检测结果。
  3. 除了患者身份之外,我不允许存储任何有关患者的信息(我没有理由)所以患者餐桌上没有任何意义。

    我如何将医生与TestResults联系起来?

    它们都有一个不存在的表的外键。即他们都有患者记录号码,但没有患者记录号码表(记录号由我无法访问的系统生成)。

    事实上,他们彼此处于多对多的关系中。


    我确实想过制作一张表来保存记录ID。该表将有一列是主键而没有别的。

    这个解决方案根本不适用于我。

    • 在管理和分析这些记录时,我的存储不可知(poco)库无法在添加新测试结果时检查患者是否在我们的系统中。
    • 即使我确实将数据库上下文传递给了管理库。这意味着系统每次想要添加测试记录时都必须进行数据库调用,以查看患者是否有任何先前的记录,或者这是否是第一个。全部在没有目的的表中添加记录。在峰值处理时间期间,这可能是每分钟数千次。如果您只是访问clr对象,那将是微不足道的事情,但如果您需要为每个对象进行数据库调用,则会完全压倒一切。

    谢谢!

1 个答案:

答案 0 :(得分:0)

尽管实际上很难实现并且可能令人望而却步,但要实施您在物理层面描述的关系,必须有一张患者表。然后,关系建模如下:

public class Doctor
{
    [Key]
    public int DoctorId {get; set;}

    public virtual ICollection<Patient> Patients {get; set;}
}

public class Patient
{
    [Key]
    public int PatientId {get; set;}

    public virtual ICollection<Doctor> Doctors {get; set;}  

    public virtual ICollection<TestResult> Results {get; set;}  
}

public class PatientMap : EntityTypeConfiguration<Patient>
{
    public PatientMap()
    {
        HasMany(p => p.Doctors)
        .WithMany(d => d.Patients)
        .Map(x => {
        x.ToTable("DoctorPatient");
        x.WithLeftKey("PatientId");
        x.WithRightKey("DoctorId");
        });
    }
}

public class TestResult
{
    [Key]
    public int ResultId {get; set;}

    public int PatientId {get; set;}

    [ForeignKey("PatientId")]
    public virtual Patient Patient {get; set;}
}

SQL只是为了清晰起见:

create table Doctor(
    DoctorId int not null primary key,
    Name nvarchar(50) not null
)

create table Patient(
    PatientId int not null primary key,
)

create table DoctorPatient(
    DoctorId int not null,
    PatientId int not null,
    primary key (DoctorId, PatientId),  
    foreign key (DoctorId) references Doctor(DoctorId),
    foreign key (PatientId) references Patient(PatientId)
)

create table TestResult(
    ResultId int not null primary key,
    PatientId int not null,
    foreign key (PatientId) references Patient(PatientId)
)