【问题标题】:Orderby lambda expression on anonymous type匿名类型上的 Orderby lambda 表达式
【发布时间】:2014-01-28 19:43:51
【问题描述】:

我重构了一个 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();
}

【问题讨论】:

  • 在加入之前尝试移动 orderby
  • 不幸的是,由于某种原因,它选择了数据库中没有 where 子句且没有连接的每一行。

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


【解决方案1】:

由于您的 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();
}

【讨论】:

  • 它抛出The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.。也将其更改为Expression&lt;Func&lt;UserProductRating, TKey&gt;&gt; orderBy,但这会引发The LINQ expression node type 'Lambda' is not supported in LINQ to Entities.
  • 对此有何其他建议?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多