【记录】AutoMapper Project To OrderBy Skip Take 正确写法

AutoMapper:Queryable Extensions

示例代码:

using (var context = new orderEntities())
{
    return context.OrderLines.Where(ol => ol.OrderId == orderId)
                .Project().To<OrderLineDTO>().ToList();
}

这是 Jimmy Bogard 提供的一段使用.Project().To的示例代码,但如果加上.OrderBy(ol => ol.OrderId).Skip(skip).Take(take)(Linq 分页)这段代码,使用 SQL Server Profiler 跟踪生成的 SQL 语句,就会发现.Project().To DTO 映射转换并没有起到效果,还是查询的所有列,在 stackoverflow 上找到一个相关的问题,他是把 Linq 分页代码放在 Project 的后面,我试过这种写法,但是会抛出异常,因为.OrderBy(ol => ol.OrderId)放在后面,访问的 OrderId 属性类型应该是 OrderLineDTO,而不是 OrderLine。

错误写法:

using (var context = new orderEntities())
{
    return context.OrderLines.Where(ol => ol.OrderId == orderId)
                .OrderBy(ol => ol.OrderId).Skip(skip).Take(take).Project().To<OrderLineDTO>().ToList();
                //或者 .Project().To<OrderLineDTO>().OrderBy(ol => ol.OrderId).Skip(skip).Take(take).ToList();
}

测试可用的正确写法:

using (var context = new orderEntities())
{
    return context.OrderLines.Where(ol => ol.OrderId == orderId)
                .OrderBy(ol => ol.OrderId).Project().To<OrderLineDTO>().Skip(skip).Take(take).ToList();
}
原文地址:https://www.cnblogs.com/xishuai/p/automapper-project-to-orderby-skip-take.html