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總是呼籲例如MapFromEntity
每ClientCourseIndexIte
?或者,有沒有更好的方法來做到這一點?
順便說一句,我仍然經常在編輯模型中使用明確的MapFromEntity
調用,而不是索引模型。
@ k0sta,我可以這樣做一般,還是我需要一個類型轉換器每個視圖模型? – ProfK 2012-07-11 03:54:54
@ProfK我已經更新了相應的答案。 – k0stya 2012-07-11 05:56:10
如果我在概括我的解決方案時調用base.MapFromEntity,我遇到一些嚴重問題。我會嘗試修復並再次進行小修改。 – ProfK 2012-07-14 08:07:46