Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell AutoMapper to use a method on my destination type?

I have the following two base view model classes, which all my view models (ever) derive from:

public class MappedViewModel<TEntity>: ViewModel
{
    public virtual void MapFromEntity(TEntity entity)
    {
        Mapper.Map(entity, this, typeof (TEntity), GetType());
    }
}

public class IndexModel<TIndexItem, TEntity> : ViewModel
    where TIndexItem : MappedViewModel<TEntity>, new()
    where TEntity : new()
{
    public List<TIndexItem> Items { get; set; }
    public virtual void MapFromEntityList(IEnumerable<TEntity> entityList)
    {
        Items = Mapper.Map<IEnumerable<TEntity>, List<TIndexItem>>(entityList);
    }
}

Before I knew that AutoMapper could do lists all by itself, like above in MapFromEntityList, I used to run a loop and call MapFromEntity on a new instance of MappedViewModel for every list item.

Now I have lost the opportunity to override only MapFromEntity because it isn't used by AutoMapper, and I have to also override MapFromEntityList back to an explicit loop to achieve this.

In my app startup, I use mapping configs like this:

Mapper.CreateMap<ClientCourse, ClientCourseIndexItem>();

How do I tell AutoMapper to always call MapFromEntity on e.g. every ClientCourseIndexIte? Or, is there a much better way to do all this?

BTW, I do still often use explicit MapFromEntity calls in edit models, not index models.

like image 931
ProfK Avatar asked Nov 22 '25 06:11

ProfK


1 Answers

You can implement a converter which calls MapFromEntity method. Here is the example:

public class ClientCourseConverter<TSource, TDestination>: ITypeConverter<TSource, TDestination>
       where TSource :  new()
       where TDestination : MappedViewModel<TEntity>, new()
{
    public TDestination Convert(ResolutionContext context)
    {
        var destination = (TDestination)context.DestinationValue;
        if(destination == null)
            destination = new TDestination();
        destination.MapFromEntity((TSource)context.SourceValue);
    }
}

// Mapping configuration
Mapper.CreateMap<ClientCourse, ClientCourseIndexItem>().ConvertUsing(
 new ClientCourseConverter<ClientCourse, ClientCourseIndexItem>());
like image 133
k0stya Avatar answered Nov 24 '25 22:11

k0stya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!