我有以下两个基本视图模型类,我的所有视图模型(曾经)都来自:
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
调用,而不是索引模型。
答案 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>());