LINQ Group通过无法识别的Select方法获得最高销售收益NotSupportedException

时间:2016-05-28 00:42:56

标签: c# entity-framework linq

典型的,一个User(恰好是.NET身份ApplicationUser)与许多Sale关系,并且我试图生成十大销售人员的列表。我还需要当前用户在所述列表中的排名(无论它是否排在前十名),例如。

User1   $10.00
User2   $8.50
User3   $7.00

因此,使用包含索引

Select重载

我当前的LINQ查询引发了一个关于无法识别方法的可怕的难以阅读错误 - 我认为Select方法:

var sales = this.Context.Sales
    .GroupBy(x => x.User) // ApplicationUser
    .Select((x, index) => new UserSale
    {
        UserId = x.Key.Id,
        Username = x.Key.UserName,
        SalesTotal = x.Sum(y => y.Price),
        Rank = index,
    })
    .OrderByDescending(x => x.SalesTotal);

vm.SalesRank = sales.Single(x => x.UserId == this.UserContext.Id).Rank;

vm.Sales = sales.Take(10).ToList();

其中UserSale是像这样的POCO:

public class UserSale
{
    public string UserId { get; set; }
    public string Username { get; set; }
    public decimal SalesTotal { get; set; }
    public int Rank { get; set; }
}

这个错误对我来说甚至难以破译:

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[MyApp.Models.UserSale] Select[IGrouping`2,UserSale](System.Linq.IQueryable`1[System.Linq.IGrouping`2[MyApp.Models.ApplicationUser,MyApp.Models.Sale]], System.Linq.Expressions.Expression`1[System.Func`3[System.Linq.IGrouping`2[MyApp.Models.ApplicationUser,MyApp.Models.Sale],System.Int32,MyApp.Models.UserSale]])' method, and this method cannot be translated into a store expression.

我一直在审查GroupBy的各种重载,我很确定这是我想要的。我还缺少什么?

2 个答案:

答案 0 :(得分:1)

问题是您的选择过载使用情况。 EF不支持此功能。 请参阅:https://msdn.microsoft.com/en-us/library/bb738550(v=vs.100).aspx

更一般地说,EF不支持具有“索引”(即序列)的IQueryable扩展方法。

答案 1 :(得分:0)

EF不支持使用2个参数进行选择,因此您需要先选择一个匿名对象,然后转换为Enumerable,然后选择获取如下的排名:

var sales = this.Context.Sales
    .GroupBy(x => x.User) // ApplicationUser
    .Select(x =>
    {
        UserId = x.Key.Id,
        Username = x.Key.UserName,
        SalesTotal = x.Sum(y => y.Price)
    })
    .OrderByDescending(x => x.SalesTotal)
    .AsEnumerable()
    .Select((x, index) => new UserSale
    {
        UserId = x.UserId,
        Username = x.Username,
        SalesTotal = x.SalesTotal,
        Rank = index,
    });