[英]Getting values depending of condition
我是asp.net的新手。 对于一些人,我的问题扰乱了社区。
我有一个查询从存储过程中检索数据,如下所示:
result = context.GetEmployeeTraining(idTraining,
idArea,
idDepartment,
type ? "(1),(2)" : "(3)").ToList();
我有这个查询来检索分支列表:
IGenericRepository<Employee> employee = new GenericRepository<Employee>();
var branchList = employee.GetList(x => x.BranchOfficeId == userId).ToList();
如何过滤第一个查询的结果以仅获取branchList
中的branchList
?
首先,我试图从以下条件得到它:
result = context.GetEmployeeTraining(idTraining,
idArea,
idDepartment,
type ? "(1),(2)" : "(3)")
.Where(x => x.BranchOfficeId == userId).ToList();
但它只获得一个值而不是像我的branchList
那样的列表
var branchList = employee.GetList(x => x.BranchOfficeId == userId).ToList();
GetEmployeeTraining
存储过程:
public virtual ObjectResult<EmployeeTraining> GetEmployeeTraining(Nullable<int> idTraining,
Nullable<int> idArea,
Nullable<int> idDepartment,
string type)
区域查询
IGenericRepository<Area> area = new GenericRepository<Area>();
var areaList = area.GetList(x => x.Id == idArea).Select(x => x.Id);
result = context.GetEmployeeTraining(idTraining, idArea, idDepartment, type ? "(1),(2)" : "(3)")
.Where(x => branchList.Any(b => b.BranchOfficeId == x.BranchOfficeId) && areaList.Contains(x.Id))
.ToList();
一种方法是使用.Any
:
var branchList = employee.GetList(x => x.BranchOfficeId == userId);
var result = context.GetEmployeeTraining(idTraining,
idArea,
idDepartment,
type ? "(1),(2)" : "(3)")
.Where(x => branchList.Any(b => b.BranchOfficeId == x.BranchOfficeId))
.ToList();
如果您查询branchList
的查询,另一个选项是使用Contains
:
var branchList = employee.GetList(x => x.BranchOfficeId == userId)
.Select(x => x.BranchOfficeId);
var result = context.GetEmployeeTraining(idTraining,
idArea,
idDepartment,
type ? "(1),(2)" : "(3)")
.Where(x => branchList.Contains(x.BranchOfficeId))
.ToList();
正如Haitham在评论中提到的,以及我要求查看GetEmployeeTraining
函数的原因, Where
调用存储过程之后添加这些Where
条件意味着过滤发生在内存中。 如果不是存储过程,您将在linq中执行这些查询(并将GetEmployeeTraining
作为扩展方法),然后添加额外的Where
将过滤数据库中的结果。
您应该更改您的过程以接受表类型参数并将分支列表传递给它,因为在这种情况下EF不会为您生成动态SQL,并且在调用过程之后的任何过滤都将在内存中。
因此,如果您的程序返回500名员工,并且所选分支的结果是50,那么您浪费了资源来检索额外的450条记录
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.