2011-02-27 181 views
5

我有幾個表,它們都是用多對多的關係互相引用而不是正常的類型。實體框架多對多的關係沒有主鍵

通常,多對多關係具有連接表,該連接表連接主鍵上的其他兩個表。

在我的情況下,我有幾個表彼此通過共享匹配的外鍵相互關聯。

我有兩張表的病歷。

  1. 分配給患者的醫生。
  2. 患者檢查結果。

我不允許存儲除患者身份以外的任何關於患者的信息(我沒有理由),因此在患者表中沒有任何意義。

我如何將醫生與測試結果聯繫起來?

它們都有一個不存在的表的外鍵。即它們都具有患者記錄號碼,但沒有患者記錄號碼錶(記錄號碼由我無法訪問的系統生成)。

所以實際上它們處於彼此之間的多對多關係。


我確實想過製作一個表來保存記錄ID。該表將有一列是主鍵,而沒有別的。

該解決方案根本不適用於我。

  • 如果添加新的測試結果,我的存儲不可知(poco)庫將無法檢查患者是否在我們的系統中。
  • 即使我確實將數據庫上下文傳遞給管理庫。這意味着系統每次需要添加測試記錄時都需要進行數據庫調用,以查看患者是否有任何以前的記錄,或者這是否是第一次。所有在沒有目的的表格中添加記錄。在高峯處理時間,這可能是每分鐘數千次。如果你只是訪問clr對象,那麼這樣做可能是微不足道的,但如果你需要爲每一個對象創建一個數據庫調用,那麼這種做法是完全壓倒性的。

謝謝!

+1

這打破了關係數據庫建模的規則,所以它不會同出一橋錶鏈接支持記錄 – 2011-08-03 05:04:08

+0

我很確定患者需要存在於你想做的事情中。 – Derek 2013-11-29 08:50:18

回答

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) 
)