且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

插入操作与许多一对多关系使用EF

更新时间:2022-12-31 15:10:16

这个怎么样?

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,您可以尝试以下方法:

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