【问题标题】:How to instruct automapper to ignore nested entity when they are null如何指示自动映射器在嵌套实体为空时忽略它们
【发布时间】:2016-10-04 22:14:28
【问题描述】:

我正在使用 Automapper 使用命名约定自动展平对象

这些是我的实体

class Student 
{
   string Name;
   Address Address;
}
class Address
{
   string Street;
   string City;
}

学生可以有或没有地址:

student1 = new Student {Name= "Rob", Address = new Address { Street = "my address", City = "Milan" }};
student2 = new Student {Name= "Tom" };

这是我的 DTO

class Student 
{
   string Name;
   string AddressStreet;
}

这是我的映射配置文件:

CreateMap<Student, StudentDto>();

映射第一个学生工作正常,但映射第二个学生

studentdto2 = _mapper.Map<Student, StudentDTO>(student2);

给我一​​个 NullReference 异常

问题:如何指示自动映射器 Student.Address 属性是可选的并且当它为空时不映射它?

【问题讨论】:

    标签: automapper


    【解决方案1】:

    问题在于您使用的 Automapper 版本。在最新的 automapper 版本 (v 5.1.l) 中不会出现此问题。您可以切换到最新版本,看看相同的代码是否有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多