插入操作与许多一对多关系使用EF [英] Insert operation with many-to-many relationship using EF

查看:291
本文介绍了插入操作与许多一对多关系使用EF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个示范类:

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。

My DbContext name is JobsContext.

以上code产生我3个表的考生,乔布斯和放大器; CandidatesJobs(由EF自动生成)

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

现在我在作业表记录:ID = 1,名称=销售:ID = 2,名称=工程师

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

我要到一个新的候选人,我会被插入到表中考生与职位表中的2个记录联系起来。

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.

我如何做到这一点使用实体框架5?

How do I do this using 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,您可以尝试以下方法:

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

这篇关于插入操作与许多一对多关系使用EF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆