繁体   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