消除LET运算符和SqlFunction

时间:2018-05-13 04:54:09

标签: c# entity-framework linq c#-4.0

请考虑此查询:

from r in ent.MyTable
group r by new { r.EmployeeName, r.EmployeeID } into g
let c = " (" + SqlFunctions.StringConvert((decimal?)g.Count()) + " )"
select new
{
    EmployeeName = g.Key.EmployeeName + c ,
    EmployeeID = g.Key.EmployeeID
});

效果很好。当我想要使用此查询时,我收到错误:

from r in ent.MyTable
group r by new { r.EmployeeName, r.EmployeeID } into g
select new
{
    EmployeeName = g.Key.EmployeeName + " (" + g.Count() + ")",
    EmployeeID = g.Key.EmployeeID
});

错误:

  

无法将System.Object转换为System.String

我该怎么做?

2 个答案:

答案 0 :(得分:0)

为什么不对输出进行双重转换?

WEBSITE_RUN_FROM_ZIP

答案 1 :(得分:0)

因此,您有一个MyTable,其中表中的每一行(可能是行)至少具有属性EmployeeIdEmployeeName

您要将表中的行分组为EmployeeIdEmployeeName相等的组。对于每个组,您都希望使用公用的{EmployeeName” +雇员数的形式来使用公用EmployeeId和该组中的雇员数。

var result = ent.MyTable                   // take MyTable
   .GroupBy(employee => new                // group all rows of this table into groups
   {                                       // with equal EmployeeId and EmployeeName
       Id = employee.EmployeeId,
       Name = employee.EmployeeName,
   })
   .Select(group => new                    // from every group make one object
   {                                       // with properties:
       EmployeeId = group.Key.Id,          // - the common employeeId
       EmployeeName = group.Key.Name       // - the common employeeName + the string value 
           + group.Count().ToString(),     //   of the number of elements in the group
   });