AutoMapper generic mapping

前端 未结 2 1675
臣服心动
臣服心动 2021-02-18 17:42

I have searched on Stack Overflow and googled about it but I haven\'t been able to find any help or suggestion on this.

I have a class like the following which create a <

相关标签:
2条回答
  • 2021-02-18 18:05

    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));
        }
    
    }
    
    0 讨论(0)
  • 2021-02-18 18:26

    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<>));
    
    0 讨论(0)
提交回复
热议问题