WebAPI控制器中的自动映射器

Ctr*_*eat 14 .net c# automapper asp.net-web-api

我有一个Car WebAPI控制器方法如下 - 注意_carService.GetCarData返回CarDataDTO对象的集合

[HttpGet]
[Route("api/Car/Retrieve/{carManufacturerID}/{year}")]
public IEnumerable<CarData> RetrieveTest(int carManufacturerID, int year)
{
    //Mapper.Map<>
    var cars = _carService.GetCarData(carManufacturerID, year);
    //var returnData = Mapper.Map<CarData, CarDataDTO>();
    return cars;
}
Run Code Online (Sandbox Code Playgroud)

CarData是我创建的WebAPI模型.

public class CarData
{
    public string Model { get; set; }
    public string Colour { get; set; }
    //other properties removed from brevity
}
Run Code Online (Sandbox Code Playgroud)

CarDataDTO是我创建的类,它为DB表建模 - 我通过使用dapper调用的存储过程检索数据.

public class CarDataDTO
{
    public int CarID { get; set; }
    public int CarManufacturerID { get; set; }
    public int Year { get; set; }
    public string Model { get; set; }
    public string Colour { get; set; }
    //other properties removed from brevity
}
Run Code Online (Sandbox Code Playgroud)

如果我在API控制器中的var cars行上有断点,我可以看到按预期返回的所有内容,并且我有一组CarDTO对象.但是,我不需要WebAPI返回CarDataID,CarID或Year,这就是我创建CarData API模型的原因.

如何轻松使用Automapper来映射我关注的属性?

我需要在WebApiConfig类中设置一些东西吗?

Jin*_*ish 38

您可以从以下位置安装AutoMapper nuget包:AutoMapper 然后声明一个类,如:

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

然后在你的Global.asax中调用它,如下所示:

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

如果您想忽略某些属性,那么您可以执行以下操作:

Mapper.CreateMap<Source, Destination>()
  .ForMember(dest => dest.SomePropToIgnore, opt => opt.Ignore())
Run Code Online (Sandbox Code Playgroud)

您使用它进行映射的方式是:

DestinationType obj = Mapper.Map<SourceType, DestinationType>(sourceValueObject);
List<DestinationType> listObj = Mapper.Map<List<SourceType>, List<DestinationType>>(enumarableSourceValueObject);
Run Code Online (Sandbox Code Playgroud)