13

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

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

4

2 回答 2

19

您需要做的是将此查询分为两个不同的步骤;第一个将检索正确的结果,第二个将数据投影到您的 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();
于 2013-05-24T17:11:56.743 回答
3

我认为问题在于您试图ToArray在 SQL 提供程序转换为 SQL 查询的块内调用。当然,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();

于 2013-05-24T17:08:38.930 回答