[英]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. 之前我知道AutoMapper可以在任务列表全部由自己,像上面
MapFromEntityList
,我用来运行一个循环,并呼吁MapFromEntity
上的一个新实例MappedViewModel
每一个列表项。
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. 现在我失去了仅覆盖
MapFromEntity
的机会,因为它不被AutoMapper使用,我还必须将MapFromEntityList
重写回显式循环来实现这一点。
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
? 如何告诉AutoMapper始终在例如每个
ClientCourseIndexIte
上调用MapFromEntity
? 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. 顺便说一下,我仍然经常在编辑模型中使用显式
MapFromEntity
调用,而不是索引模型。
You can implement a converter which calls MapFromEntity method. 您可以实现一个调用MapFromEntity方法的转换器。 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>());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.