【问题标题】:LINQ to Entities does not recognize the method 'Int32 ToInt32 Converting String to IntLINQ to Entities 无法识别方法“Int32 ToInt32 Converting String to Int”
【发布时间】:2013-09-09 09:15:31
【问题描述】:

我有一个 LINQ 语句,我想对某个字符串类型的单个列进行求和。

我正在尝试在 Converting.ToInt32 的位置执行以下语句。当我运行它时,我收到以下错误。

LINQ to Entities 无法识别方法 'Int32 ToInt32(System.String)' 方法,这个方法不能翻译 到商店表达式中。

LINQ 语句

    var CoreData = new
    {
    Shoots =
   (from item in coresdb.Productions
    where item.Date >= StartShift && item.Date <= EndDate
   select item).Sum(x => Convert.ToInt32(x.ShootCount)
   )
};

我也尝试了许多不同的数据类型来转换并得到类似的错误。

【问题讨论】:

标签: linq


【解决方案1】:

您无法将ToInt32 转换为 T-SQL。使其工作的一种方法是根据从数据库中检索到的列表在内存中运行它,如下所示

var CoreData = coresdb.Productions
    .Where(item => item.Date >= StartShift && item.Date <= EndDate)
    .ToList()  // get the data into memory first.
    .Sum(x => Convert.ToInt32(x.ShootCount));

更新:将 ToList() 移到 where 子句之后。

【讨论】:

    【解决方案2】:

    如果您不想具体化查询(检索数据),您可以使用强制转换(即 (int) x.ShootCount)。转换为 SQL CAST AS 语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多