EF Core with Postgres is generating negative primary keys

c# entity-framework entity-framework-core postgresql

Question

I'm using Entity Framework Core with the Postgres provider, each entity has an int primary key with ValueGeneratedOnAdd. This has been working perfectly up until now. Every now and then I nuke my migrations and database and start fresh with dotnet ef migrations add InitialDb. After this last refresh my primary keys have started generating from what I assume is int.Min -2147482647. They used to start at 1.

I'm not sure what caused this and I would like to go back to having the primary keys increment from 1. Is there a way to accomplish this?

1
2
12/9/2016 7:12:46 AM

Accepted Answer

I found something that I changed in the code that caused this behavior. In my base repository when adding a new entity I changed DbContext.Set<T>().Add(entity) to DbContext.Attach(entity).State = EntityState.Added;

The reason I did this was because when using attach EF will automatically detect existing related entities. Using only add would try and add related entities again whether they already exist in the db or not.

I have no idea why it would suddenly switch to a negative int when generating the ID.

1
12/12/2016 5:53:23 AM

Popular Answer

EF Core generates temporary IDs which are then replaced with the real IDs when SaveChanges is called. It's by design behavior.



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