Automapper in WebAPI Controller

后端 未结 1 1482
你的背包
你的背包 2021-02-01 07:05

I have a Car WebAPI controller method as below - note _carService.GetCarData returns a collection of CarDataDTO objects

[HttpGet]
[Route(\"api/Car/Retrieve/{carM         


        
相关标签:
1条回答
  • 2021-02-01 07:57

    You could install the AutoMapper nuget package from: AutoMapper And then declare a class like:

    public class AutoMapperConfig
    {
        public static void Initialize()
        {
            Mapper.Initialize((config) =>
            {
                config.CreateMap<Source, Destination>().ReverseMap();
            });
        }
    }
    

    And then call this in your Global.asax like this:

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AutoMapperConfig.Initialize();
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
    

    And if you would like to ignore certain properties then you could do something like this:

    Mapper.CreateMap<Source, Destination>()
      .ForMember(dest => dest.SomePropToIgnore, opt => opt.Ignore())
    

    And the way you use this for mapping is:

    DestinationType obj = Mapper.Map<SourceType, DestinationType>(sourceValueObject);
    List<DestinationType> listObj = Mapper.Map<List<SourceType>, List<DestinationType>>(enumarableSourceValueObject);
    
    0 讨论(0)
提交回复
热议问题