user2963570 user2963570 - 1 year ago 155
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download