2016-12-06 75 views
1

我如何添加一條記錄自動生成表「RelativesPatients」,並將它們連接在一起時,我有使用實體框架兩個表的對象?自動生成許多到許多表,添加新記錄到它

public ActionResult CreateConnection() {  
    var relative = _context.Relatives.Single(r => r.Id == viewModel.RelativeId); 
    var patient = _context.Patients.Single(p => p.Id == viewModel.PatientId); 

    patient.Relatives.Add(relative); 
    _context.SaveChanges(); 
} 

public class Relative 
{ 
    public int Id { get; set; } 
    public ICollection<Patient> Patients { get; set; } 
} 

public class Patient 
{ 
    public int Id { get; set; } 
    public ICollection<Relative> Relatives { get; set; } 
} 
+0

這看起來是正確的。你看到一個錯誤?另一種可能的方式:https://lostechies.com/jimmybogard/2014/03/12/avoid-many-to-many-mappings-in-orms/ –

+0

由於某種原因,病人給了我一個空引用異常。 Relatives.Add(相對);但我有它上面的對象。 –

回答

2

您需要爲您的藏品構造函數:

public class Relative 
{ 
    public Relative() 
    { 
     Patients = new Collection<Patient>(); 
    } 
    public int Id { get; set; } 
    public ICollection<Patient> Patients { get; set; } 
} 

public class Patient 
{ 
    public Patient() 
    { 
     Relatives = new Collection<Relative>(); 
    } 
    public int Id { get; set; } 
    public ICollection<Relative> Relatives { get; set; } 
} 

,或者您也可以手動新建起來:

patient.Relatives = new Collection<Relative>(); 
patient.Relatives.Add(relative);