我正在尝试编写一个将投影到DTO的查询,其中两个属性是int数组。由于投影中的ToArray()调用,我收到错误。
teams = context
.Teams
.Include("TeamDepartments")
.Include("TeamEmployees")
.Select(t => new TeamDto
{
sourceSystemId = t.TeamId,
name = t.Name,
manager = t.EmployeeIdTeamManager,
teamLead = t.EmployeeIdTeamLead,
employees = t.TeamEmployees.Select(te => te.EmployeeId).ToArray(),
departments = t.TeamDepartments.Select(td => td.DepartmentId).ToArray()
})
.ToList();
对于两个int []属性的员工和部门,如何获取这些值?现在,我只是撤回团队列表,然后循环遍历它们以创建DTO。
我见过其他类似的问题,但解决方案对我来说似乎没有用。我怀疑我需要采取额外的步骤,因为我正在穿越一段关系。
答案 0 :(得分:15)
您需要做的是将此查询分为两个不同的步骤;第一个将检索正确的结果,第二个将数据投影到您的DTO。像这样:
teams = context
.Teams
.Include("TeamDepartments")
.Include("TeamEmployees")
.Select(t => new // notice this is an anonymous object
{
sourceSystemId = t.TeamId,
name = t.Name,
manager = t.EmployeeIdTeamManager,
teamLead = t.EmployeeIdTeamLead,
employees = t.TeamEmployees.Select(te => te.EmployeeId),
departments = t.TeamDepartments.Select(td => td.DepartmentId)
})
.ToList() // first run the query on the server without the ToArray calls
.Select(obj => new TeamDto
{ // then project the in-memory results onto your DTO.
sourceSystemId = obj.sourceSystemId,
name = obj.name,
manager = obj.manager,
teamLead = obj.teamLead,
employees = obj.employees.ToArray(),
departments = obj.departments.ToArray()
})
.ToList();
答案 1 :(得分:2)
我认为问题在于您尝试在SQL提供程序转换为SQL查询的块中调用ToArray
。当然,SQL Server不知道数组是什么,所以方法不起作用。如果您删除ToArray
电话会怎样?我相信这些结果会以IEnumberables
的形式返回到该块之外,您可以根据需要进行转换。我不确定这会有效,但如果您通过以下方式更改TeamDto
定义,则可能会解决问题。
// you have now something like
string[] employees;
// instead do
IEnumberable<string> employees;
// If you want an array add
string[] _employees;
然后在_employees = employees.ToArray();