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

Rab*_*bbi 5 many-to-many entity-framework

我有一些表,它们都是多对多的关系,但不是正常的关系.

通常,多对多关系具有连接表,该连接表连接其主键上的两个其他表.

在我的情况下,我有几个表通过共享匹配的外键相互关联.

我有两张桌子的病历.

  1. 分配给患者的医生.
  2. 患者检测结果.

除了患者身份之外,我不允许存储任何有关患者的信息(而且我没有理由)所以患者餐桌上没有任何意义.

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

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

所以事实上他们彼此处于多对多的关系中.


我确实想过制作一张桌子来保存记录ID.那个表有一列是主键而没有别的.

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

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

谢谢!

Ben*_*ind -1

尽管这是微不足道的,而且可能令人望而却步,但为了在物理层面上强化您所描述的关系,必须有一张患者表。那么关系简单建模如下:

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;}
}
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,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)
)
Run Code Online (Sandbox Code Playgroud)