我有疑问:
ctx.PrintJobs
.GroupBy(pj => pj.Department.Name)
.Select(g => new PrintJobReportItem
{
A3SizePercentage = g.Sum(p => p.DocumentSize == "a3" ? p.TotalPhisicalPages : 0d) / g.Sum(p => p.TotalPhisicalPages) * 100,
...
}
它有效。
我有很多Perecentage值要计算,所以我试着将这段代码重构为:
ctx.PrintJobs
.GroupBy(pj => pj.Department.Name)
.Select(g => new PrintJobReportItem
{
A3SizePercentage = g.PercentageOf(p => p.DocumentSize == "a3"),
...
}
...
public static class GroupingEx
{
public static double PercentageOf(this IGrouping<string, PrintJobItem> g, Func<PrintJobItem, bool> trueCondition)
{
return g.Sum(p => trueCondition(p) ? p.TotalPhisicalPages : 0d) / g.Sum(p => p.TotalPhisicalPages) * 100;
}
}
但后来我收到了错误:
System.NotSupportedException : LINQ to Entities does not recognize the method 'Double PercentageOf...
我明白为什么我会收到这个错误。 是否有其他方法可以将Linq 2 Entity支持的方法组提取到单个方法中?或者我是否复制粘贴相同的代码位? Linq 2对象不是一个选项
答案 0 :(得分:1)
有可能在ESQL中(内联函数被复制到多个ESQL查询 - example),如果您使用EDMX可以定义model defined function,则可以使用Linq到实体。我首先知道代码(=没有EDMX)不支持 - 在这种情况下,你必须使用@Daniel提到的方法来实现结果并使用linq-to-objects来执行你的方法。
答案 1 :(得分:0)
您可以先从数据库中获取数据,然后在本地数据上使用您的方法:
ctx.PrintJobs.GroupBy(pj => pj.Department.Name)
.ToList()
.Select(g => new PrintJobReportItem
{
A3SizePercentage =
g.PercentageOf(p => p.DocumentSize == "a3"),
...
}