我有一个像这样的Api方法PATCH
[HttpPatch("{id}")]
public async Task<IActionResult>UpdateCity(int id, [FromBody] JsonPatchDocument<CityUpdateDto> patchDoc)
{
var cityFromRepo = await _citiesRepository.GetCityById(id);
var cityToPatch = _mapper.Map<CityUpdateDto>(cityFromRepo);
Action<JsonPatchError> errorAction = error =>{ ModelState.AddModelError(error.Operation.path, error.ErrorMessage);};
patchDoc.ApplyTo(cityToPatch, errorAction);
//this line below
_mapper.Map(cityToPatch, cityFromRepo);
await _citiesRepository.SaveChangesAsync();
return Ok("Done update");
}
这是原始方法,正在更新数据。
但我将代码更改为
[HttpPatch("{id}")]
public async Task<IActionResult>UpdateCity(int id, [FromBody] JsonPatchDocument<CityUpdateDto> patchDoc)
{
var cityFromRepo = await _citiesRepository.GetCityById(id);
var cityToPatch = _mapper.Map<CityUpdateDto>(cityFromRepo);
Action<JsonPatchError> errorAction = error =>{ ModelState.AddModelError(error.Operation.path, error.ErrorMessage);};
patchDoc.ApplyTo(cityToPatch, errorAction);
//changed here
_mapper.Map<City>(cityToPatch);
await _citiesRepository.SaveChangesAsync();
return Ok("Done update");
}
现在我的补丁方法不起作用了。
我想知道原因和解释
_mapper.Map(cityToPatch, cityFromRepo);
mapper.map(T Source,T Destination)
VS
_mapper.Map<City> (cityFromRepo);
mapper.Map<T Destination> (T Source);
请告诉我详细的答案。
一个返回目标类型的新实例,另一个将映射到现有实例。
最常见的用法是返回一个新实例,例如:
var source = new FooSource
{
MyProperty = 123
};
var destination = mapper.Map<FooDestination>(source);
但是,如果您已经有一个实例,则可以将属性映射到该实例中:
var source = new FooSource
{
MyProperty = 123
};
var destination = new FooDestination();
// destination.MyProperty == 0
mapper.Map(source, destination);
// destination.MyProperty == 123
请注意,后一个重载将也返回该对象,尽管您不需要使用它。