根据条件获取值

时间:2016-10-17 22:11:35

标签: c# asp.net-mvc linq

我在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中的项?

首先,我试图从以下条件中获取它:

 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();

2 个答案:

答案 0 :(得分:0)

一种方法是使用.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条件意味着过滤发生在内存中。如果不是存储过程,您可以在linq中执行这些查询(例如,将GetEmployeeTraining作为扩展方法),然后添加额外的Where将过滤数据库中的结果。

答案 1 :(得分:0)

您应该更改您的过程以接受表类型参数并将分支列表传递给它,因为在这种情况下EF不会为您生成动态SQL,并且在调用过程之后的任何过滤都将在内存中。

因此,如果您的程序返回500名员工,并且所选分支的结果为50,那么您浪费了资源来检索额外的450条记录