【记录】AutoMapper Project To not support ResolveUsing

示例代码:

public List<OrderLineDTO> GetLinesForOrder(int orderId)
{
    Mapper.CreateMap<OrderLine, OrderLineDTO>()
            .ForMember(dto => dto.Item, conf => conf.MapFrom(ol => ol.Item.Name)
            .ForMember(dto => dto.Name, opt => opt.ResolveUsing<NameCustomResolver>());

    using (var context = new orderEntities())
    {
        return context.OrderLines.Where(ol => ol.OrderId == orderId)
                .Project().To<OrderLineDTO>().ToList();
    }
}
public class NameCustomResolver : ValueResolver<OrderLine, string>
{
    protected override string ResolveCore(OrderLine source)
    {
        //可以加一些逻辑
        return source.Name;
    }
}

按照上面代码编写会抛出异常,使用 ORM 获取转换的时候(.Project().To),是不支持 ResolveUsing 的,Jimmy Bogard(AutoMapper 作者)应该扩展下 Queryable Extensions,如果不使用 .Project().To,单纯的映射转换是支持 ResolveUsing 的,使用 ResolveUsing 无非就是方便业务逻辑代码编写,我们也可以使用 MapFrom 进行实现:

public List<OrderLineDTO> GetLinesForOrder(int orderId)
{
    Mapper.CreateMap<OrderLine, OrderLineDTO>()
            .ForMember(dto => dto.Item, conf => conf.MapFrom(ol => ol.Item.Name)
            .ForMember(dto => dto.Name, opt => opt.MapFrom(ol => NameCustomResolver(ol)));

    using (var context = new orderEntities())
    {
        return context.OrderLines.Where(ol => ol.OrderId == orderId)
                .Project().To<OrderLineDTO>().ToList();
    }
}
public static string NameCustomResolver(OrderLine source)
{
    //可以加一些逻辑
    return source.Name;
}

参考资料:

  • Queryable Extensions
  • Automapper Project.To Null reference exception
  • Automapper error: Expressions mapping from methods not supported yet
  • Projekt().To in AutoMapper.QueryableExtensions fails when inner property is null

你可能感兴趣的:(【记录】AutoMapper Project To not support ResolveUsing)