我有两个模型类:

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

我的DbContext名称是JobsContext。

上面的代码为我生成了3个表Candidates,Jobs和CandidatesJobs(由EF自动生成)

现在,我在Jobs表中记录了:Id = 1,名称=“销售”:Id = 2,名称=“工程师”。

我想将要插入到Candidates表中的新候选人与Jobs表中的2条记录相关联。

在插入候选人之前,我知道Jobs表的ID,并且我不希望调用数据库以从Jobs表中获取更多详细信息。

如何使用Entity Framework 5做到这一点?

最佳答案

这个怎么样?

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

仅当您已经在DbContext的同一实例中从数据库中获取了作业时,这才起作用,否则EF会认为该作业是“新的”并尝试将其插入。如果您只有ID,则可以尝试以下操作:
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();

关于c# - 使用EF具有多对多关系的插入操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19130983/

10-09 05:37
查看更多