我有以下两个基本 View 模型类,我的所有 View 模型(曾经)都派生自它们:
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
调用。
最佳答案
您可以实现一个调用 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>());
关于c# - 我怎样才能告诉 AutoMapper 在我的目标类型上使用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11419578/