Search code examples
c#automapperautofac

How to cast entity with included object to other entity in AutoMapper?


I'm using AutoMapper in my project and I need to cast a domain entity with an included object into a view model. The included object is a current state of the domain entity which has current characteristics of a object. The view model has characteristics properties on the same level with other properties (without an included object) because I think it is better solution. I tried to use this code in MapperProfile:

CreateMap<DomainEntity, ViewModel>
    .ForMember(...)
    ...
    .ForPath(dest => dest, opt => opt.MapFrom(source => 
Mapper.Map<IncludedEntity, ViewModel>(source.Child)));

But this solution throws exeption "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance."

I'm using Autofac and mapper instance. How can I do it?

UPDATE

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

UPDATE 2

My mappings:

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());

So, I to want cast DomaintEntity by one string:

var viewModel = _mapper.Map<Balloon, BalloonDetailDto>(balloon);

Solution

  • I found work solution in comments to this question: How to use AutoMapper to map destination object with a child object in the source object?

    It need use this:

    .ConstructUsing((source, ctx) => ctx.Mapper.Map<IncludedEntity, ViewModel>(source.Child))
    

    instead this:

    .ForPath(dest => dest, opt => opt.MapFrom(source =>
    Mapper.Map<IncludedEntity, ViewModel>(source.Child)));