簡體   English   中英

AutoMapper 通用映射

[英]AutoMapper generic mapping

我已經在 Stack Overflow 上搜索過並在谷歌上搜索過,但我找不到任何幫助或建議。

我有一個類似下面的類,它創建一個PagedList對象,並且還使用 AutoMappper 將類型從源映射到目標。

public class PagedList<TSrc, TDest>
{
    protected readonly List<TDest> _items = new List<TDest>();

    public IEnumerable<TDest> Items {
        get { return this._items; }
    }
}

我想為這種類型創建一個地圖,應該將其轉換為另一種類型,如下所示

public class PagedListViewModel<TDest>
{
    public IEnumerable<TDest> Items { get; set; }
}

我試過

Mapper.CreateMap<PagedList<TSrc, TDest>, PagedListViewModel<TDest>>();

但是編譯器會因為TSrcTDestTDest

有什么建議嗎?

根據AutoMapper wiki

public class Source<T> {
    public T Value { get; set; }
}

public class Destination<T> {
    public T Value { get; set; }
}

// Create the mapping
Mapper.CreateMap(typeof(Source<>), typeof(Destination<>));

在你的情況下,這將是

Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>));

這是最佳實踐:

第一步:創建一個泛型類。

public class AutoMapperGenericsHelper<TSource, TDestination>
{
    public static TDestination ConvertToDBEntity(TSource model)
    {
        Mapper.CreateMap<TSource, TDestination>();
        return Mapper.Map<TSource, TDestination>(model);
    }
}

第二步:使用它

[HttpPost]
public HttpResponseMessage Insert(LookupViewModel model)
{
    try
    {
        EducationLookup result = AutoMapperGenericsHelper<LookupViewModel, EducationLookup>.ConvertToDBEntity(model);
        this.Uow.EducationLookups.Add(result);
        Uow.Commit(User.Id);
        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    catch (DbEntityValidationException e)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, CustomExceptionHandler.HandleDbEntityValidationException(e));
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex.HResult.HandleCustomeErrorMessage(ex.Message));
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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