Search code examples
c#asp.netentity-framework-6aspnetboilerplate

repository.InsertAsync always returns entity.Id 0


Sometimes I need Id of inserted entity. To achieve this, I use:

entity = await _repository.InsertAsync(entity);

With this, entity.Id is always 0. Because of this, I'm adding the line below.

await CurrentUnitOfWork.SaveChangesAsync();

If I add this line, I can get the Id. But, this way seems dirty to me. Is there another way? Or is this way already correct? I just want to be sure. I want to know that using CurrentUnitOfWork will not be cause problems that I may not know. Thank you.


Solution

  • There is InsertAndGetIdAsync for when you explicitly need the Id.

    var entityId = await _repository.InsertAndGetIdAsync(entity);