0

I am creating a new EntityObject that do not exist in the database (SQLite). I populate the object's properties and join it to parent object. I am not populating the primary key property because as I understand EF should automatically generate a temporary EntityKey to me. Then I use AddObject method to add the newly created EntityObject to the context and after that I call SaveChanges.

I receive UpdateException: Abort due to constraint violation PRIMARY KEY must be unique. I see the primary key property is always set to 0 although it should be the next available value in the database, right? I checked that in the database the primary key field is autoincrementing.

What should I do to get EF to give me a temporary EntityKey?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Nuts
  • 2,755
  • 6
  • 33
  • 78

1 Answers1

0

EF doesn't create temporary keys for you. You'll need to generate the temporary key by yourself.

What you can do: add a property in your model decorated with [NotMapped] attribute. In object creation, this value should be initialized with a value. Guids resolve the problem finely. You just have to use Guid.NewGuid() to generate a temporary key for you.

[NotMapped] ensures you the field will be not persisted in database.

Leonel Sanches da Silva
  • 6,972
  • 9
  • 46
  • 66
  • Here the problem was in the database itself. It didn't autoincrement the primary key in the database table and the case is now solved. – Nuts Feb 24 '14 at 10:38