Rasmus Rajje Josefsson
Rasmus Rajje Josefsson

Reputation: 1574

Autogenerated Many-to-Many Table, add a new record to it

How can I add a record into the autogenerated table "RelativesPatients" and link them together when I have an object from both tables using 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; }
}

Upvotes: 1

Views: 58

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

You need a constructor for your collections:

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; }
}

or you can new them up manually:

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

Upvotes: 2

Related Questions