簡體   English   中英

如何告訴AutoMapper在目標類型上使用方法?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM