我在项目中使用AutoMapper,并且需要将包含对象的域实体转换为视图模型。 所包含的对象是具有对象的当前特性的域实体的当前状态。视图模型具有与其他属性(不包含对象)处于同一级别的特征属性,因为我认为这是更好的解决方案。 我试图在MapperProfile中使用此代码:
CreateMap<DomainEntity, ViewModel>
.ForMember(...)
...
.ForPath(dest => dest, opt => opt.MapFrom(source =>
Mapper.Map<IncludedEntity, ViewModel>(source.Child)));
但是此解决方案会抛出异常“ Mapper未初始化。使用适当的配置调用Initialize。如果尝试通过容器或其他方式使用Mapper实例,请确保您没有对静态Mapper.Map的任何调用。方法,如果您使用的是ProjectTo或UseAsDataSource扩展方法,请确保传递适当的IConfigurationProvider实例。“
我正在使用Autofac和mapper实例。 我该怎么办?
更新
DomainEntity:
public class Balloon : BaseIdEntity
{
public int Id { get; set; }
public string FactoryNumber { get; set; }
/// <summary>
/// it's CurrentState of balloon.
/// </summary>
public BalloonSnapshot ActualSnapshot { get; set; }
public int? ActualSnapshotId { get; set; }
}
CurrentState:
public class BalloonSnapshot : BaseIdEntity
{
public int Id { get; set; }
/// <summary>
/// It's parent Domaint entity.
/// </summary>
public Balloon Balloon { get; set; }
public int BalloonId { get; set; }
public DateTime Date { get; set; }
}
ViewModel:
public class BalloonDetailDto
{
public int Id { get; set; }
public string FactoryNumber { get; set; }
public DateTime? Date { get; set; }
}
更新2
我的映射:
CreateMap<Balloon, BalloonDetailDto>
.ForPath(dest => dest, opt => opt.MapFrom(source =>
Mapper.Map<BalloonSnapshot, BalloonDetailDto>(source)));
CreateMap<BalloonSnapshot, BalloonDetailDto>()
.ForMember(s => s.Id, opt => opt.Ignore());
因此,我想通过一个字符串强制转换DomaintEntity:
var viewModel = _mapper.Map<Balloon, BalloonDetailDto>(balloon);
答案 0 :(得分:0)
我在对此问题的评论中找到了工作解决方案:How to use AutoMapper to map destination object with a child object in the source object?
它需要使用这个:
.ConstructUsing((source, ctx) => ctx.Mapper.Map<IncludedEntity, ViewModel>(source.Child))
相反:
.ForPath(dest => dest, opt => opt.MapFrom(source =>
Mapper.Map<IncludedEntity, ViewModel>(source.Child)));