如何告诉AutoMapper在目标类型上使用方法?

时间:2012-07-10 18:28:36

标签: c# .net asp.net-mvc automapper

我有以下两个基本视图模型类,我的所有视图模型(曾经)都来自:

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

在我知道AutoMapper可以单独列出所有内容之前,就像上面MapFromEntityList一样,我曾经为每个列表运行一个循环并在MapFromEntity的新实例上调用MappedViewModel项目

现在我失去了仅覆盖MapFromEntity的机会,因为它没有被AutoMapper使用,我还必须覆盖MapFromEntityList回到显式循环来实现这一点。

在我的应用启动中,我使用这样的映射配置:

Mapper.CreateMap<ClientCourse, ClientCourseIndexItem>();

如何告诉AutoMapper始终致电MapFromEntity。每ClientCourseIndexIte?或者,有更好的方法来做这一切吗?

顺便说一句,我仍然经常在编辑模型中使用显式MapFromEntity调用,而不是索引模型。

1 个答案:

答案 0 :(得分:2)

您可以实现一个调用MapFromEntity方法的转换器。这是一个例子:

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