I noticed a weird thing today when I tried to save an entity and return its id in EF Core
Before: After:
I was thinking about if it was before calling saveChanges() but it works with another entity with a similar setup.
ps: I use unit of work to save all changes at the end.
What was the reason?
It will be negative until you save your changes. Just call Save
on the context.
_dbContext.Locations.Add(location); _dbContext.Save();
After the save, you will have the ID which is in the database. You can use transactions, which you can roll back in case there's a problem after you get the ID.
The other way would be not to use the database's built-in IDENTITY fields, but rather implement them yourself. This can be very useful when you have a lot of bulk insert operations, but it comes with a price — it's not easy to implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With