LINQ to Entities 无法识别 ToArray

问题描述 投票:0回答:2

我正在尝试编写一个查询,该查询将投影到 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。

我见过其他类似的问题,但解决方案似乎对我不起作用。我怀疑我需要采取额外的步骤,因为我正在经历一段关系。

c# linq-to-entities
2个回答
20
投票

您需要做的是将这个查询分成两个不同的步骤;第一个将检索正确的结果,第二个将把数据投影到 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();

4
投票

我认为问题在于您尝试在 SQL 提供程序转换为 SQL 查询的块内调用

ToArray
。当然,SQL Server 不知道数组是什么,因此该方法不起作用。如果删除
ToArray
调用会发生什么?我相信这些结果将在该块之外以
IEnumerables
的形式返回,您可以根据需要转换它们。我不确定这是否有效,但如果您按以下方式更改
TeamDto
定义,可能会解决问题。

 // you have now something like
 string[] employees;

 // instead do
 IEnumerable<string> employees;

 // If you want an array add
 string[] _employees;

然后在查询之外

_employees = employees.ToArray();

© www.soinside.com 2019 - 2024. All rights reserved.