![](/img/trans.png)
[英]How can I use Automapper to map an object to an unknown destination type?
[英]How can I tell AutoMapper to use a method on my destination type?
我有以下两个基本视图模型类,我的所有视图模型(曾经)派生自:
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始终在例如每个ClientCourseIndexIte
上调用MapFromEntity
? 或者,有更好的方法来做这一切吗?
顺便说一下,我仍然经常在编辑模型中使用显式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>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.