简体   繁体   中英

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 eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM