Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core Add function returns negative id

I noticed a weird thing today when I tried to save an entity and return its id in EF Core

Before: The Id is 0 before it was added to database After: Now the id has been changed to a negative value

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?

like image 614
Aven Avatar asked Jan 19 '17 02:01

Aven


Video Answer


1 Answers

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.

like image 73
Dawid Rutkowski Avatar answered Sep 17 '22 16:09

Dawid Rutkowski