【问题标题】:Doing Sum() on a set of anonymous type: is it possible?对一组匿名类型执行 Sum():可能吗?
【发布时间】:2013-12-03 06:24:28
【问题描述】:

如果我从查询中选择匿名类型 (select new):

 var smsPerGroup = from g in db.Groups
                   select new
                   {
                       GroupName = g.Name,
                       ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
                   };

碰巧我不能 sum() :

int max = smsPerGroup.Max(g => g.ReceivedSMS);  // ERROR!

抛出的错误是: There was an error parsing the query.

对此最正确的解决方案是什么?

我不想在这个查询中创建一个只使用一次的类。

是否有可能有一个 “不是很匿名” 类型?这是:定义其属性的类型而不是类本身的类型

类似这样的:(语法不正确)

    ...
   select new
   {
       string GroupName = g.Name,
       int ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
   };




编辑:详细错误如下

There was an error parsing the query. [ Token line number = 6,Token line offset = 5,Token in error = SELECT ]

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. [ Token line number = 6,Token line offset = 5,Token in error = SELECT ]

Source Error: 


Line 159:                                      };
Line 160:
Line 161:                    int max = smsPerGroup.Max(g => g.ReceivedSMS);

【问题讨论】:

  • 如果这是 EF(或任何提供者),请添加适当的标签。并非所有 LINQ 都是平等的。还要确保包含 full 消息 - 这应该包含异常类型。
  • 我认为您的查询没有任何问题。你能再描述一下你的错误吗?它是运行时错误的编译吗?有没有抛出异常?
  • @MarcinJuraszek 这是可以从 SQL Server 查询生成的异常消息.. 但最好让 OP 这么说并包含 full详情。
  • 我添加了详细的错误。是英孚。

标签: linq entity-framework anonymous-types


【解决方案1】:

一个简单的解决方案是在调用 .Sum() 之前使用 .ToList() 实现查询:

var test = (from g in db.Groups
            select new
            {
                GroupName = g.Name,
                ReceivedSMS = g.Members.SelectMany(p => p.ReceivedSMS).Count()
            }).ToList();

var sum = test.Sum(t => t.ReceivedSMS);

【讨论】:

  • 这成功了!担心它会延迟查询,但它做得很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多