Patrice Cote
Patrice Cote

Reputation: 3716

ASP.NET MVC 4 ModelState not valid when passing key

I have an ASP.NET MVC 4 WebApi. I use Entity Framework as my ORM (database first). The DB has only one test table with a few fields with an int "id" set as identity (auto increment).

I just try to implement basic CRUD with a javascript client, but I always get ModelState.IsValid = false when I get to the POST method. I parsed the error and saw that is was coming from the "id" field, which has a value of 0. How does the api manage this kind of auto-increment keys ? What does it expect to receive in the "id" field ?

Everything is based on the template. I didn't change any code to the WebApi generated controller. All other operations (Read, Update, Delete) are working fine.

EDIT : Note that if I bypass the ModelState.IsValid() test, the data is saved in the DB and everything works... But obviously, that's not what I want to do.

EDIT 2 : I discovered that the identity property in a databse is handled by the StoreGeneratedPattern property on the id field in the EDMX. Possible values are : "Computed", "Identity" and "None". In my case, it's set to "Identity".

Upvotes: 2

Views: 1162

Answers (1)

Romil Gandhi
Romil Gandhi

Reputation: 49

Check validation not put on ID in your model.Put Id as autogenrated.

Upvotes: 2

Related Questions