【问题标题】:Automapper in WebAPI ControllerWebAPI 控制器中的自动映射器
【发布时间】:2017-03-15 14:19:42
【问题描述】:

我有一个 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;
}

CarData 是我创建的一个 WebAPI 模型。

public class CarData
{
    public string Model { get; set; }
    public string Colour { get; set; }
    //other properties removed from brevity
}

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
}

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

如何轻松使用 Automapper 仅映射我关心的属性?

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

【问题讨论】:

  • 您的基本模型和 DTO 模型是倒退的 - DTO 类应该是您通过网络传输的内容,而非 DTO 类应该代表实际的 DB 对象

标签: c# .net asp.net-web-api automapper


【解决方案1】:

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

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

然后像这样在 Global.asax 中调用它:

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

如果你想忽略某些属性,那么你可以这样做:

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

你使用它来映射的方式是:

DestinationType obj = Mapper.Map<SourceType, DestinationType>(sourceValueObject);
List<DestinationType> listObj = Mapper.Map<List<SourceType>, List<DestinationType>>(enumarableSourceValueObject);

【讨论】:

  • 您好 Jinish - 这将如何在实际的 API 方法中使用?
  • 最后,一个帮助我让它工作的答案!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 2020-03-19
相关资源
最近更新 更多