自动生成多对多表,向其添加新记录

时间:2016-12-06 15:21:48

标签: c# entity-framework linq

如何在自动生成的表格中添加记录" 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; }
}

1 个答案:

答案 0 :(得分: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);