.net核心linq选择重载索引不起作用



在添加select索引重载之前,我得到了一个linq lambda select代码。以前,我得到了记录列表,但我需要索引,我用它为每个记录分配一个唯一的Id。当我用ToList()添加时,我得到一个没有错误/内部异常的异常。我能让代码不抛出错误的唯一方法是使用.AsEnumberable(),但我需要一个列表。我读了很多关于.ToList()超负荷工作的帖子,但我一直并没有成功。

这是我的代码和我试图修复这个

var emps = this.DbContext.Employees
.GroupJoin(this.DbContext.Depts,
employee => employee.EmployeeId,
dept => dept.EmployeeId,
(employee, dept) => new { employee, dept }
)
.SelectMany(
employee_dept_left => employee_dept_left.dept.DefaultIfEmpty(),
(employee_dept_left, dept) => new { employee_dept_left, dept }
)
.Join(this.DbContext.Divs,
emp_emp_dept => emp_emp_dept.employee_dept_left.employee.DivId,
division => division.DivId,
(emp_emp_dept, division) => new { emp_emp_dept, division }
)
.Where(s => !string.IsNullOrEmpty(filter.selectedDiv))
.GroupBy(grouped => new
{
grouped.emp_emp_dept.employee_dept_left.employee.EmployeeId,
grouped.emp_emp_dept.employee_dept_left.employee.LastNm,
grouped.emp_emp_dept.employee_dept_left.employee.FirstNm,
grouped.emp_emp_dept.employee_dept_left.employee.DivId
})
.Select((joined, index) => new EmployeeViewModel
{
Id = index,
EmployeeId = joined.Key.EmployeeId,
LastNm = joined.Key.LastNm.Trim(),
FirstNm = joined.Key.FirstNm.Trim(),
DivisionId = joined.Key.DivId,
}).ToList();

错误信息显示

无法翻译。以可翻译的形式重写查询,或者通过插入对"AsEnumerable"、"AsAsyncEnumerable)"、"ToList"或"ToListAsync"的调用,显式切换到客户端评估。看见https://go.microsoft.com/fwlink/?linkid=2101038了解更多信息。

我尝试使用.AsEnumerable()而不是.ToList():

List<EmployeeViewModel> test = emps.Cast<EmployeeViewModel>().ToList();

但这引发了一个例外。

非常感谢您的帮助。

提前感谢

Select当前无法翻译为SQL的问题。您可以使用AsEnumerable()进行额外的选择以解决问题。

...
.Select(joined => new 
{
EmployeeId = joined.Key.EmployeeId,
LastNm = joined.Key.LastNm.Trim(),
FirstNm = joined.Key.FirstNm.Trim(),
DivisionId = joined.Key.DivisionId,
})
.AsEnumerable()
.Select((x, index) => new EmployeeViewModel
{
Id = index,
EmployeeId = x.EmployeeId,
LastNm = x.LastNm,
FirstNm = x.FirstNm,
DivisionId = x.DivisionId,
}).ToList();

请注意,当存在联接时,查询在查询语法中更具可读性。

var query = 
from employee in this.DbTracsContext.Employees
join dept in his.DbTracsContext.Depts on employee.EmployeeId equals dept.EmployeeId into employee_dept_left
from dept in employee_dept_left.DefaultIfEmpty()
join division in this.DbTracsContext.Depts on employee.DivisionId equals division.DivisionId
where string.IsNullOrEmpty(filter.DivisionSelection) || filter.DivisionSelection == "0" || employee.DivisionId == filter.DivisionSelection
group employee by new { employee.EmployeeId, employee.LastNm, employee.FirstNm, employee.DivisionId } into g
select new
{
EmployeeId = g.Key.EmployeeId,
LastNm = g.Key.LastNm.Trim(),
FirstNm = g.Key.FirstNm.Trim(),
DivisionId = g.Key.DivisionId,
};
var emps = query
.AsEnumerable()
.Select((x, index) => new EmployeeViewModel
{
Id = index,
EmployeeId = x.EmployeeId,
LastNm = x.LastNm,
FirstNm = x.FirstNm,
DivisionId = x.DivisionId,
}).ToList();

相关内容

  • 没有找到相关文章

最新更新