user2963570 user2963570 - 6 months ago 51
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.


public ActionResult Create(HotelsViewModel hotelsViewModel)
if (ModelState.IsValid)
HotelsDTO hotelDTO = _mapper.Map<HotelsDTO>(hotelsViewModel);

_hotelService.AddHotelAmenities(hotelDTO.Id, hotelsViewModel.SelectedAmenities);

return RedirectToAction("Index");

return View(hotelsViewModel);


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

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?


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