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;
}




本文转自田园里的蟋蟀博客园博客,原文链接:http://www.cnblogs.com/xishuai/p/automapper-project-to-null-reference-exception.html,如需转载请自行联系原作者

相关文章
JavaWeb - No URLs will be polled as dynamic configuration sources
JavaWeb - No URLs will be polled as dynamic configuration sources
648 0
JavaWeb - No URLs will be polled as dynamic configuration sources
|
Java Maven
Maven打包出现webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
Maven打包出现webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
659 0
|
Java Maven
使用maven构建项目报错Cannot change version of project facet Dynamic Web Module to 3.0解决方案
使用maven构建项目报错Cannot change version of project facet Dynamic Web Module to 3.0解决方案
使用maven构建项目报错Cannot change version of project facet Dynamic Web Module to 3.0解决方案
build.xml:391: javac doesn‘t support the “nativeheaderdir“ attribute
build.xml:391: javac doesn‘t support the “nativeheaderdir“ attribute
110 0
Faceted project metadata file "/.settings/org.eclipse.wst.common.project.facet.core.xml" could
Faceted project metadata file "/.settings/org.eclipse.wst.common.project.facet.core.xml" could
169 0
Faceted project metadata file "/.settings/org.eclipse.wst.common.project.facet.core.xml" could
|
Web App开发 Java 关系型数据库
eclipse上依据hibernate tools逆向生成PO(Domain Object)的过程
使用eclipse开发一个基于java的maven的web项目,业务逻辑基于spring实现,数据库服务器采用mysql。我们项目的业务逻辑(面向对象)和数据(关系型数据库)之间,依靠hibernate进行映射、对应、使用和处理。
3769 0