gpt4 book ai didi

c# - 删除连接表,如何插入一行而不在数据库中查询该行引用的实体?

转载 作者:行者123 更新时间:2023-12-03 11:31:06 24 4
gpt4 key购买 nike

假设我们有一个简单的架构:

Employee
--------
Id
EmployeeName


Project
-------
Id
ProjectName


EmployeeProject
---------------
EmployeeId
ProjectId

在 EF 的早期版本中,我记得连接表被添加到模型中(或者可能它总是被省略,我正在考虑一个具有附加列的表)。在 EF 6 中,该表被省略,模型如下所示:

EF Model

是否有任何方法可以将行添加到连接表,而无需先查询数据库来获取适当的实体?例如,如果我想创建一个新项目,我可能会从前端获取员工 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
}

最佳答案

不必先检索这些项目。使用断开连接的对象时,您只需附加现有实体或将状态更改为未更改

Entity Framework takes care of tracking the state of entities while they are connected to a context, but in disconnected or N-Tier scenarios you can let EF know what state your entities should be in.

更多:http://msdn.microsoft.com/en-us/data/jj592676

您可以只附加员工以减少数据库往返。

foreach(var id in employeeIds)
{
var employee = new Employe { Id = id };
db.Set<Employee>().Attach(employee); // context.Entry(employee).State = EntityState.Unchanged;
proj.Employees.Add(employee);
}

关于c# - 删除连接表,如何插入一行而不在数据库中查询该行引用的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25244852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com