1

我已经在 Linqer 中尝试了以下 LINQ 查询,它工作正常,但是当我尝试使用 C# 时它给出了以下错误

from IHeal_Mnt_Tickets in iHealEntities.iHeal_Mnt_Tickets
    where
        Tickets.Active == 1 &&
        Tickets.MntID == 1 &&
        Tickets.InsertedOn >= fromdate && 
        Mnt_Tickets.InsertedOn <= todate &&
        (new string[] { "Resolved", "Assigned" }).Contains(Tickets.status)
        group Tickets by new {
            Tickets.Instance
        } into g
            select new {
              Instance = g.Key.Summus_Instance,
              Assigned = (Int64?)g.Count(p => p.iHealID != null),
              resolved = (System.Int64?)g.Sum(p => (p.status == "Resolved" ? 1 : 0)),
              domain = (System.Int64?)g.Sum(p => (p.status == "Assigned" ? 1 : 0)),
              iHeal_Closure = (Decimal?)Math.Round((Double)(Double)g.Sum(p => (p.iHeal_Cur_status == "Resolved" ? 1 : 0)) * 1.0 / (Double)g.Count(p => p.iHealID != null) * 100, 2, MidpointRounding.AwayFromZero)
            };

错误是

"LINQ to Entities does not recognize the method 'Double Round(Double, Int32, System.MidpointRounding)' method, and this method cannot be translated into a store expression."
4

1 回答 1

9

并非 BCL 中支持的所有内容在 SQL 中都具有直接等效项。鉴于这是查询的最后一部分,最简单的方法是只编写一个查询来获取您需要的所有数据而无需四舍五入等,然后使用本地查询将该数据转换为您喜欢的格式:

var dbQuery = from item in source
              where filter
              select projection;
// The AsEnumerable() part is key here
var localQuery = from item in dbQuery.AsEnumerable()
                 select complicatedTransformation;

有效地使用AsEnumerable()只是更改编译时类型......因此Select调用Enumerable.Select使用的是委托而不是Queryable.Select使用表达式树。

我希望您可以使最终的转换您当前的方法简单得多 - 像(Double)(Double)真的没有必要这样的事情......无论何时转换doubledecimal或反之亦然,您都应该质疑这是必要的还是可取的......通常最好坚持使用二进制浮点十进制浮点,而不是混合它们。

于 2014-09-19T12:30:35.223 回答