C# WebAPI控制器中的Automapper
我有一个Car WebAPI控制器方法,如下所示-注意\u carService.GetCarData将Cardata的集合返回给对象C# WebAPI控制器中的Automapper,c#,.net,asp.net-web-api,automapper,C#,.net,Asp.net Web Api,Automapper,我有一个Car WebAPI控制器方法,如下所示-注意\u carService.GetCarData将Cardata的集合返回给对象 [HttpGet] [Route("api/Car/Retrieve/{carManufacturerID}/{year}")] public IEnumerable<CarData> RetrieveTest(int carManufacturerID, int year) { //Mapper.Map<> var ca
[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;
}
CardataTo是我创建的一个类,它对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或Year,这就是我创建CarDataAPI模型的原因
如何轻松地使用Automapper只映射我关心的属性
我需要在我的WebApiConfig类中设置什么吗?您可以从以下位置安装AutoMapper nuget软件包: 然后声明一个类,如:
public class AutoMapperConfig
{
public static void Initialize()
{
Mapper.Initialize((config) =>
{
config.CreateMap<Source, Destination>().ReverseMap();
});
}
}
如果你想忽略某些属性,你可以这样做:
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())
Mapper.CreateMap()
.FormMember(dest=>dest.SomePropToIgnore,opt=>opt.Ignore())
您使用此映射的方式是:
DestinationType obj = Mapper.Map<SourceType, DestinationType>(sourceValueObject);
List<DestinationType> listObj = Mapper.Map<List<SourceType>, List<DestinationType>>(enumarableSourceValueObject);
DestinationType obj=Mapper.Map(sourceValueObject);
List listObj=Mapper.Map(enumarableSourceValueObject);
Hi Jinish-这将如何在实际的API方法中使用?最后,一个帮助我使其工作的答案!谢谢您的基本模型和DTO模型是反向的-DTO类应该是您通过线路传输的对象,而非DTO类应该表示实际的DB对象
DestinationType obj = Mapper.Map<SourceType, DestinationType>(sourceValueObject);
List<DestinationType> listObj = Mapper.Map<List<SourceType>, List<DestinationType>>(enumarableSourceValueObject);