EF Core Add function returns negative id

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.

Leave a Comment

tech