在匿名类型上的orderby lambda表达式

时间:2014-01-10 00:30:36

标签: c# entity-framework lambda linq-to-entities expression

我重构了一个linq到实体查询以加快它并打破了我的orderby lambda功能。

有没有办法让它再次运行,因为查询现在是一个连接并创建一个匿名类型?

由于orderBy而被破坏的重构代码:

public List<UserProductRating> GetUserProductRatings<TKey>(int userId, IPager pager, Func<UserProductRating, TKey> orderBy)
{
    var result = _userProductRatingRepo.Table.Where(a => a.UserId == userId)
        .Join(_productRepo.Table, outer => outer.ProductId, inner => inner.ProductId,
        (outer, inner) => new { UserProductRating = outer, Product = inner })
        .OrderByDescending(o => orderBy) // won't work because the query creates an anonymous type above that doesn't match the Func<> definition
        .Skip(pager.Skip).Take(pager.PageSize)
        .Select(a => new
        {
            a.UserProductRating.UserId,
            a.UserProductRating.ProductId,
            a.UserProductRating.VoteCount,
            a.UserProductRating.TotalViews,
            a.UserProductRating.Rating,
            a.Product.Name
        }).ToList();
}

适用于orderBy的旧代码:

public List<UserProductRating> GetUserProductRatings<TKey>(int userId, IPager pager, Func<UserProductRating, TKey> orderBy)
{
    return _userProductRatingRepo.Table
                .Include(a => a.Product)
                .Where(a => a.UserId == userId)
                .OrderByDescending(orderBy)
                .Skip(pager.Skip)
                .Take(pager.PageSize)
                .ToList();
}

1 个答案:

答案 0 :(得分:0)

由于您的OrderBy参数需要UserProductRating并且您将其包含为匿名类型的属性之一,因此您应该可以执行此操作:

public List<UserProductRating> GetUserProductRatings<TKey>(int userId, IPager pager, Func<UserProductRating, TKey> orderBy)
{
    var result = _userProductRatingRepo.Table.Where(a => a.UserId == userId)
        .Join(_productRepo.Table, outer => outer.ProductId, inner => inner.ProductId,
        (outer, inner) => new { UserProductRating = outer, Product = inner })
        .OrderByDescending(o => orderBy(o.UserProductRating)) // <-- pass the joined property to the order function 
        .Skip(pager.Skip).Take(pager.PageSize)
        .Select(a => new
        {
            a.UserProductRating.UserId,
            a.UserProductRating.ProductId,
            a.UserProductRating.VoteCount,
            a.UserProductRating.TotalViews,
            a.UserProductRating.Rating,
            a.Product.Name
        }).ToList();
}