假设我们有一个简单的模式:
Employee
--------
Id
EmployeeName
Project
-------
Id
ProjectName
EmployeeProject
---------------
EmployeeId
ProjectId
在早期版本的 EF 中,我记得连接表被添加到模型中(或者它可能总是被省略,我正在考虑一个有额外列的表)。在 EF 6 中,表格被省略,模型如下所示:
有没有办法在不首先查询数据库以获得适当的实体的情况下向联结表添加行?例如,如果我想创建一个新项目,我可能会从前端获取一个员工 ID 列表;我必须查询数据库以获取员工,然后将它们添加到项目的员工集合中,然后再次访问数据库进行保存。有没有办法只调用一次数据库就可以做到这一点?
更新
这是我要解决的示例(伪代码):
CreateProject (string name, List<int> employeeIds)
{
var proj = new Project;
proj.ProjectName = name;
context.Projects.Add(proj);
foreach(var id in employeeIds)
{
// we have the id, but we need to get the actual Employee entity by hitting the database
var employee = context.Employees.First(e => e.Id == id);
proj.Employees.Add(employee);
}
context.SaveChanges();
}
如果模型中存在连接表,我可以简单地执行以下操作:
CreateProject (string name, List<int> employeeIds)
{
var proj = new Project;
proj.ProjectName = name;
context.Projects.Add(proj);
foreach(var id in employeeIds)
{
var empProj = new EmployeeProject();
empProj.Project = proj;
// we don't have the Employee entity, but we can set the Id and everything works.
empProj.EmployeeId = id;
context.EmployeeProjects.Add(empProj);
}
context.SaveChanges(); // only need to hit database once, after all entities have been added
}