AutoMapper generic mapping

时光怂恿深爱的人放手 提交于 2019-12-08 14:41:44

问题


I have searched on StackOverflow and googled about it but I havent been able to find any help or suggestion on this.

I have a class like the following wich create a PagedList object and also uses AutoMappper to map types from source to destination

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

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

I would like to create a Map for this type that should convert it to another type like the following

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

I have tried with

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

but the compiler complains because of TSrc and TDest

Any suggestion?


回答1:


According to the 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<>));

In your case this would be

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



回答2:


This is a best practice:

first step: create a generice class.

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

Second step: Do Use it

[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));
    }

}


来源:https://stackoverflow.com/questions/29380976/automapper-generic-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!