[英]Orderby lambda expression on anonymous type
我将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
参数采用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.