map(s,d)和map<d>(s)的核心区别是什么

问题描述 投票:0回答:1

我有一个像这样的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);

请告诉我详细的答案。

c# mapping webapi
1个回答
0
投票

一个返回目标类型的新实例,另一个将映射到现有实例。

最常见的用法是返回一个新实例,例如:

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

请注意,后一个重载将返回该对象,尽管您不需要使用它。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.