Search code examples
c#asp.net-mvcentity-frameworkmany-to-many

Insert operation with many-to-many relationship using EF


I've two model classes:

public class Candidate
{
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Job> Jobs { get; set; }
}

public class Job
{
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Candidate> Candidates { get; set; }
}

My DbContext name is JobsContext.

The above code generates me 3 tables Candidates, Jobs & CandidatesJobs(autogenerated by EF)

Now I've records in Jobs table : Id = 1, Name = "Sales" : Id = 2, Name = "Engineer".

I want to associate a new Candidate which I'll be inserting into Candidates table with the 2 records from Jobs table.

Before inserting the Candidate I know the Id's of the Jobs table & I don't wish to make a call to the database to get more details from Jobs table.

How do I do this using Entity Framework 5?


Solution

  • 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<Job>(); // 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();