首页 > 解决方案 > 如何使用 AutoMapper 从 ASP.NET Core Web API 发布方法中插入的实体获取 Id 值

问题描述

我的 ASP.NET Core Web API 有以下Post方法在数据库中插入一个新的类别实体:

public async Task<ActionResult> Post([FromBody] CategoryDTO categoryDto)
{
      if (categoryDto == null)
            return BadRequest("Invalid Data");

       await _categoryService.Add(categoryDto);

       return new CreatedAtRouteResult("GetCategory", new { id = categoryDto.Id }, categoryDto);
}

我正在使用 AutoMapper,因此我从正文请求发送 DTO,并CategoryService使用 AutoMapper 映射获取实体并使用我的存储库(使用 EF Core SaveChanges)创建它:

public async Task Add(CategoryDTO categoryDto)
{
     var categoryEntity = _mapper.Map<Category>(categoryDto);
     await _categoryRepository.Create(categoryEntity);
}

以这种方式创建了实体,但在 Post 方法中,返回的 id 值CreateAdRouteResult为零,因为它从 获取 id 值CategoryDto

如何获取插入的实体的 id 值?

是否有任何替代方法可以使用 AutoMapper 执行此操作并获取已创建实体的 id 值?

标签: postasp.net-core-webapi

解决方案


I solved the problem by assigning the entity Id (categoryEntity) to categoryDto.Id in my service:

public async Task Add(CategoryDTO categoryDto)
{
     var categoryEntity = _mapper.Map<Category>(categoryDto);
     await _categoryRepository.Create(categoryEntity);
     categoryDto.Id = categoryEntity.Id; 
}

推荐阅读