自动映射表达式错误:空引用/错误映射类型和反向映射

时间:2016-11-21 23:29:19

标签: c# automapper automapper-5

我正在尝试使用AutoMapper在表达式中的两个模型之间进行映射,但是从AutoMapper接收错误:“错误映射类型”,内部异常消息“对象引用未设置为对象的实例。” / p>

我设置了我的配置并按照Github上的wiki定义了映射:

Configuration

Expression Translation

以下是使用版本AutoMapper 5.1.1生成错误的非常简化示例。

要映射的模型

注意:我只需要从Model1映射到Model2。

public class Model1
{
    public int Id { get; set; }
}

public class Model2
{
    public int Id { get; set; }
} 

配置:

public static class AutoMapperConfig
{
    public static IMapper Mapper;

    static AutoMapperConfig()
    {
        var config = new MapperConfiguration(c => {
          // Produces error
          CreateMap<Model1, Model2>();

          //The below definitions do NOT produce error
          CreateMap<Model1, Model2>().ReverseMap();
          //OR
          CreateMap<Model1, Model2>();
          CreateMap<Model2, Model1>();
          //OR
          CreateMap<Expression<Func<Model1,bool>>, Expression<Func<Model2,bool>>>();

        });

        Mapper = config.CreateMapper();
    }
}

用法:

Expression<Func<Model1, bool>> model1Expr = x => x.Id == 2;
var model2Expr =  AutoMapperConfig.Mapper.Map<Expression<Func<Model2,bool>>>(model1Expr);

我在声明上面的model2Expr变量的行中收到错误。

来自Elmah的错误:(

[NullReferenceException: Object reference not set to an instance of an object.]
AutoMapper.Mappers.MappingVisitor.PropertyMap(MemberExpression node) +109
AutoMapper.Mappers.MappingVisitor.VisitMember(MemberExpression node) +95
System.Linq.Expressions.MemberExpression.Accept(ExpressionVisitor visitor) +14
System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) +22
AutoMapper.Mappers.MappingVisitor.VisitBinary(BinaryExpression node) +73
System.Linq.Expressions.BinaryExpression.Accept(ExpressionVisitor visitor) +14
System.Linq.Expressions.ExpressionVisitor.Visit(Expression node) +22
AutoMapper.Mappers.ExpressionMapper.Map(TSource expression, ResolutionContext context) +1534
lambda_method(Closure , Object , Object , ResolutionContext ) +183

[AutoMapperMappingException: Error mapping types.

重要:同事注意到,在定义双向映射时(使用ReverseMap或两个单独的CreateMap语句)或者将映射明确定义为在Expression之间时,不会遇到错误类型。上面的表达式翻译链接确实定义了模型之间的双向映射,但没有明确提到需要它。

问题:

我是否在某种程度上弄乱了配置和/或映射定义,或者是在表达式中的对象之间进行映射时所需的双向映射定义,而wiki只是没有明确说明它?

更新 我在AutoMapper GitHub上打开了一个问题。 截至目前,似乎

  

是的,在进行表达式翻译时,顺序是倒退的。

基本上这意味着如果要在表达式之间进行映射,请在所需映射的相反方向创建映射定义:

CreateMap<Model2, Model1>();
//....
Expression<Func<Model1, bool>> model1Expr = x => x.Id == 2;
var model2Expr =  AutoMapperConfig.Mapper.Map<Expression<Func<Model2,bool>>>(model1Expr);

1 个答案:

答案 0 :(得分:0)

您需要按如下方式调用ReverseMap:

static AutoMapperConfig()
{
    var config = new MapperConfiguration(c => {
      CreateMap<Model1, Model2>().ReverseMap(); // <======
    });

    Mapper = config.CreateMapper();
}