I\'ve two model classes:
public class Candidate
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection Jobs { get
How about this?
Job salesJob; // already fetched from db
Job engineerJob; // already fetched from db
Candidate candidate = new Candidate();
candidate.Name = "John Doe";
candidate.Jobs = new List(); // you could also do this in the constructor of Candidate
candidate.Jobs.Add(salesJob);
candidate.Jobs.Add(engineerJob);
context.SaveChanges();
This only works if you already fetched the jobs from the database within the same instance of the DbContext, else EF will think that the jobs are 'new' and tries to insert them. If you only have the ids, you could try the following:
var salesJob = new Job { Id = salesJobId };
var engineerJob = new Job { Id = engineerJobId };
context.Jobs.Attach(salesJob);
context.Jobs.Attach(engineerJob);
candiate.Jobs.Add(salesJob);
candiate.Jobs.Add(engineerJob);
context.SaveChanges();