我使用的是最新版本的Automapper(12.0)。
在父DTO上应用构造函数时,">
Here My Model and DTOs:
class Maestro
{
public virtual Guid Id { get; set; }
public virtual string Nombre { get; set; }
public virtual IList<Alumno> Alumnos { get; set; }
}
class Alumno
{
public virtual Guid Id { get; set; }
public virtual string Nombre { get; set; }
}
class MaestroDto
{
public MaestroDto(System.Guid id, string nombre, List<AlumnoDto> alumnos)
{
this.Id = id;
this.Nombre = nombre;
this.Alumnos = alumnos;
}
[System.ComponentModel.DataAnnotations.Key]
[System.ComponentModel.DataAnnotations.Required()]
public System.Guid Id { get; set; }
[System.ComponentModel.DataAnnotations.Required()]
public string Nombre { get; set; }
public List<AlumnoDto> Alumnos { get; set; }
}
class AlumnoDto
{
public virtual Guid Id { get; set; }
public virtual string Nombre { get; set; }
}
请注意MaestroDto
有一个构造函数。
这是我的映射配置:
var config = new MapperConfiguration(c =>
{
c.CreateMap<Maestro, MaestroDto>().ForMember(c => c.Alumnos, opt => opt.ExplicitExpansion());
c.CreateMap<Alumno, AlumnoDto>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
当使用Automapper以这种方式进行投影时:
List<MaestroDto> resultMaestro = mapper.ProjectTo<MaestroDto>(maestros.AsQueryable()).ToList();
"Alumnos">总是加载的,即使我没有特别说过我希望它被加载。
这是由于构造函数有"MaestroDto",这是预期的吗?我希望即使有构造函数,如果我愿意,也可以忽略该属性,不将其添加到使用lambda表达式的查询中。
在这里你可以找到要点。
提前感谢。
禁用映射构造函数可以解决这个问题。
在映射初始化时添加cfg.DisableConstructorMapping()
使其工作。