user2963570 user2963570 - 2 months ago 24
C# Question

C# DTO get Id of Entity

When I want to create an entity using a DTO I want to get the Id of the recently inserted entity in the DTO that lives in my controller.

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);
}


Service:

To retrieve the Id back in my controller should I change the return type of the Create method as an integer or is there another way to make this work?

public void Create(TDTO entity)
{
T t = _mapper.Map<T>(entity);
_repository.Create(t);
_unitOfWork.Commit();
}


After the savechanges gets hit the id of t is getting set but I'm failing to retrieve the id in my DTO object back in the controller.

Any advice?

Answer

You can simply add entity.Id = t.Id; right after committing changes, i.e. right after the line: _unitOfWork.Commit();