Rab*_*bbi 5 many-to-many entity-framework
我有一些表,它们都是多对多的关系,但不是正常的关系.
通常,多对多关系具有连接表,该连接表连接其主键上的两个其他表.
在我的情况下,我有几个表通过共享匹配的外键相互关联.
我有两张桌子的病历.
除了患者身份之外,我不允许存储任何有关患者的信息(而且我没有理由)所以患者餐桌上没有任何意义.
我如何将医生与TestResults联系起来?
它们都有一个不存在的表的外键.即他们都有患者记录号码,但没有患者记录号码表(记录号由我无法访问的系统生成).
所以事实上他们彼此处于多对多的关系中.
我确实想过制作一张桌子来保存记录ID.那个表有一列是主键而没有别的.
这个解决方案根本不适用于我.
谢谢!
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)
| 归档时间: |
|
| 查看次数: |
1467 次 |
| 最近记录: |