【发布时间】: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