如何合并同一数据库中两个同属性Db Context的查询结果?
合并两个DbContext的查询结果解决方案
问题分析
你有两个DbContext,对应同一数据库中结构完全一致的员工表与员工归档表,需要合并指定ID的查询结果。现有代码存在两处问题:contact是拼写错误(应为Concat),且方法参数employeeid类型与实体属性的string不匹配。
解决方案
方案1:内存中合并(简单快速,适合小数据量)
直接用LINQ的Concat(保留重复项)或Union(自动去重)合并两个查询结果,最终转为List:
public class EmployeeService { private readonly IEmployee _employeeService; private readonly IEmployeeArchive _employeeArchiveService; public EmployeeService(IEmployee employeeService, IEmployeeArchive employeeArchiveService) { _employeeService = employeeService; _employeeArchiveService = employeeArchiveService; } public List<Employee> GetCombinedEmployees(string employeeid) { var activeEmployees = _employeeService.Queryable().Where(q => q.employeeid == employeeid); var archivedEmployees = _employeeArchiveService.Queryable().Where(q => q.employeeid == employeeid); // 用Concat保留所有匹配项(含重复),用Union则自动去除重复记录 return activeEmployees.Concat(archivedEmployees).ToList(); } }
方案2:数据库层面合并(低内存占用,适合大数据量)
若数据量较大,直接在数据库执行UNION查询,减少内存加载的数据量。由于两个DbContext指向同一数据库,可通过原生SQL实现:
public List<Employee> GetCombinedEmployeesFromDb(string employeeid) { // 假设员工表名为Employees,归档表名为EmployeeArchives var unionSql = @"SELECT employeeid, Name, FullName, MobileNumber, Age FROM Employees WHERE employeeid = @employeeId UNION SELECT employeeid, Name, FullName, MobileNumber, Age FROM EmployeeArchives WHERE employeeid = @employeeId"; // 使用任意一个DbContext执行原生SQL查询 return _employeeService.Queryable() .FromSqlRaw(unionSql, new SqlParameter("@employeeId", employeeid)) .ToList(); }
关键注意事项
- 类型匹配:实体的
employeeid是string类型,方法参数必须对应,避免隐式类型转换错误 - 重复处理:
Concat保留两个集合的重复记录,Union自动去重,根据业务需求选择 - 数据库一致性:确保两个DbContext连接同一数据库,跨库查询需额外配置
- 性能优化:大数据场景优先选数据库层面的
UNION,降低内存开销
内容的提问来源于stack exchange,提问作者Srikanth
相关产品推荐
相关产品推荐

