repository.InsertAsync always returns entity.Id 0

asp.net aspnetboilerplate c# entity-framework-6

Question

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.

1
0
1/30/2019 1:42:15 AM

Accepted Answer

There is InsertAndGetIdAsync for when you explicitly need the Id.

var entityId = await _repository.InsertAndGetIdAsync(entity);
5
1/29/2019 5:48:01 PM

Popular Answer

If it's an Identity column from the db, where the id is automatically generated, you can't get the Id value until the row is stored in the DB.

This is why you need to do the SaveChangesAsync. Before you do that, the object is in-memory but not stored in the DB yet, which is where the Id will be assigned for that object.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow