post - 如何使用 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 值?
解决方案
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;
}
推荐阅读
- javascript - 排序数据文本的问题,colspan 单元格失败
- odata - 将 Odata 模型 V2 与 sap.m.list 一起使用
- sql - SQL中不同值之间的第一个更改值
- html - HTML Button 标记中的 IE-11 链接无法正常工作 - 如何修复?
- asp.net-mvc - Bundles/images/user-img-background.jpg 404(未找到)
- python - CRFSuite 有多少训练数据?
- json - 从 API 错误中获取数据,JSON 输入意外结束
- html - 为什么表格需要 width:0 来尊重列宽?
- java - FAIL - 无法启动上下文路径 /sagar 处的应用程序
- google-chrome - 谷歌登录按钮在 Chrome 中不起作用