Let's say we have a simple schema:
Employee
--------
Id
EmployeeName
Project
-------
Id
ProjectName
EmployeeProject
---------------
EmployeeId
ProjectId
In a previous version of EF, I remember the junction table getting added to the model (or maybe it was always elided and I'm thinking of a table that had additional columns). In EF 6, the table is elided and the model looks like this:
Is there any way to add rows to the junction table without first querying the database to get the appropriate entity? E.g., if I want to create a new Project, I might get a list of Employee Ids from the front-end; I would have to query the database to get the Employees, and then add them to the Project's Employee collection, and then hit the database again to save. Is there a way to do that with only one call to the database?
Update
Here's an example of what I'm trying to solve (pseudocode):
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();
}
If the junction table existed in the model, I could simply do:
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
}