Reputation: 890
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("Staff Id")]
public int StaffId { get; set; }
My model has the above for the declaration of the Key. When I am Adding a new record I have a value of -1 in the StaffId field and I get an error: 'Cannot insert explicit value for identity column'
I don't want it to use the -1, it's an Identity column and SQL server should generate the new value on Insert.
How do I tell EF - don't pass the StaffId property to the Insert Query?
Note: Using database logging, I can see the StaffId parameter is currently being passed in. StaffId is needed and works fine for updates.
Upvotes: 2
Views: 1743
Reputation: 109185
When a column is an identity column EF still allows you to insert an explicit value for it. In some case that may come in handy, but you have to know what you do and also how to set IDENTITY_INSERT
on for the transaction (in Sql Server, other databases may have different mechanisms to achieve the same thing).
When an identity property has the default value for its type (in your case, 0
for StaffId
) EF will ignore it when inserting an entity. And also on subsequent updates, but that's standard for key properties.
If for some reason you want to be certain that any key value will be ignored on insert you can add metadata to the property:
modelBuilder.Entity<Staff>().Property(p => p.StaffId).ValueGeneratedOnAdd()
.Metadata.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore);
(This is in EF-core 5.0.9)
Upvotes: 5