Reputation: 133
I have created a basic Entity Framework test project which is making use of the Code-First approach to populate a database which has two tables.
However, I have noticed that the framework seems to be automatically assigning a value to an entry which is used as a foreign key to another table, despite the fact that I have already set the value in code.
When inspecting via the debugger I can see that the object's property is correct until the point the SaveChanges() is called, but on inspecting the database, the int which I set has been overwritten with an automatically-generated value.
I can get around this by applying the following attribute to the property:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
However, I thought that values were only automatically-generated if no value had been set in code. Am I wrong, or is such behaviour to be expected?
I have noticed that the same behaviour isn't true for a primary key which isn't acting as a foreign key.
Any help much appreciated.
Upvotes: 0
Views: 1359
Reputation: 11348
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
Annotation or Fluent API equivalent is required if using Key int Id and you wish to supply the Id.
Ef Annotations default behaviour for Id int
Upvotes: 3