c# - 我怎样才能告诉 AutoMapper 在我的目标类型上使用一个方法?

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

我有以下两个基本 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/

相关文章:

asp.net-mvc - Orchard CMS "Microsoft Azure Media Storage"模块无法连接到新的存储帐户

javascript - 在 Dotnet Highchart 中添加 javascript 函数

c# - Asp.Net 4.5 Web API - 返回 HTTP 状态代码 207

C# InvalidArgument= '1' 的值对于 'index' 无效

c# - 适用于 .NET 4.0 的 Permcalc.exe

.net - System.Drawing.FontFamily.GenericSansSerif - 什么影响它选择的底层字体?

c# - 在 C# 上使用 C++/CLI 的情况或优缺点是什么

c# - 使用Xml编写代码

c# - IQueryable,将匿名类型转换为强类型

c# - 保存已旋转的图像