Insert operation with many-to-many relationship using EF

后端 未结 3 1260
醉梦人生
醉梦人生 2020-12-29 11:42

I\'ve two model classes:

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


        
3条回答
  •  伪装坚强ぢ
    2020-12-29 12:35

    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();
    

提交回复
热议问题