当我想使用 DTO 创建实体时,我想获取 Controller 中 DTO 中最近插入的实体的 ID。
Controller :
public ActionResult Create(HotelsViewModel hotelsViewModel)
{
if (ModelState.IsValid)
{
HotelsDTO hotelDTO = _mapper.Map<HotelsDTO>(hotelsViewModel);
_hotelService.Create(hotelDTO);
_hotelService.AddHotelAmenities(hotelDTO.Id, hotelsViewModel.SelectedAmenities);
return RedirectToAction("Index");
}
return View(hotelsViewModel);
}
服务:
要在 Controller 中检索 Id,我应该将 Create 方法的返回类型更改为整数,还是有其他方法可以实现此目的?
public void Create(TDTO entity)
{
T t = _mapper.Map<T>(entity);
_repository.Create(t);
_unitOfWork.Commit();
}
在 savechanges 被命中后,t 的 id 被设置,但我无法在 Controller 中检索 DTO 对象中的 id。
有什么建议吗?
最佳答案
您只需在提交更改后添加 entity.Id = t.Id;
即可,即在以下行之后添加:_unitOfWork.Commit();
关于C# DTO 获取实体的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487569/