2016-12-06 4 views
1

自動生成テーブル "RelativesPatients"にレコードを追加し、両方のテーブルのオブジェクトをEntity Frameworkで使用しているときにそれらをリンクする方法を教えてください。自動生成された多対多テーブル

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

これは、患者の何らかの理由でNull参照例外を与えます。親族。追加(相対)。しかし、私はその上のオブジェクトを持っています。 –

答えて

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); 
関連する問題