2012-07-10 31 views
3

我有以下兩種基本視圖模型類,我所有的視圖模型(曾經)從派生:如何告訴AutoMapper在我的目標類型上使用方法?

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待辦事項列表全部由自己,像上面,我用運行一個循環並針對每個列表項目在MappedViewModel的新實例上調用MapFromEntity

現在我失去了只覆蓋MapFromEntity的機會,因爲它不被AutoMapper使用,我還必須重寫MapFromEntityList回到顯式循環來實現這一點。

在我的應用程序啓動時,我使用映射CONFIGS這樣的:

Mapper.CreateMap<ClientCourse, ClientCourseIndexItem>(); 

我如何告訴AutoMapper總是呼籲例如MapFromEntityClientCourseIndexIte?或者,有沒有更好的方法來做到這一點?

順便說一句,我仍然經常在編輯模型中使用明確的MapFromEntity調用,而不是索引模型。

回答

2

您可以實現一個調用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>()); 
+0

@ k0sta,我可以這樣做一般,還是我需要一個類型轉換器每個視圖模型? – ProfK 2012-07-11 03:54:54

+0

@ProfK我已經更新了相應的答案。 – k0stya 2012-07-11 05:56:10

+0

如果我在概括我的解決方案時調用base.MapFromEntity,我遇到一些嚴重問題。我會嘗試修復並再次進行小修改。 – ProfK 2012-07-14 08:07:46

相關問題