Entity Framework Identity Column Negative Value

asp.net-core entity-framework-core postgresql

Question

I have an ASP.NET Core 1.0 web application that implements some REST web services which interact with a PostgreSQL database via Entity Framework Core.

In my model, I have a variety of code-first entity classes that utilize the following pattern:

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Obviously this corresponds to an auto-incrementing unique key identity column in the database.

The trouble is that, undoubtedly due to some defect somewhere, occasionally for reasons I don't yet understand, the value of the Id is a very large negative integer.

-2147482645

Normally, they are well-behaved nicely ascending integer values starting at 1.

What could be causing it?

1
0
8/30/2016 3:16:57 PM

Accepted Answer

It turns out this issue had to do with calling Update() on the entity before it had even been inserted with a call to Add(). Naturally calling Update() on an non-inserted entity causes an exception to be thrown. But then catching the exception and using it as a flag that the entity needs to be added doesn't seem to be an option, as doing so consistently caused the negative Id value to be used on the subsequent insert. The solution involved detecting using other means that the entity didn't exist yet, and then properly calling Add() to insert it rather than using Update() as a default action.

0
8/30/2016 6:50:08 PM


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