I have a table that stores some extra data for some rows of a table like:
public class QuoteExtra
{
[Key]
public int QuoteId { get; set; }
// More fields here
}
I'd like to be able to add rows to this table where I explicitly set the PK.
If I simply leave it as above, setting a value and submitting the row causes the value to be discarded and replaced with the auto-generated value from the database (and the column is defined as an Identity column in the actual schema).
This appears to be the right solution:
public class QuoteExtra
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int QuoteId { get; set; }
// More fields here
}
However this instead gets me the exception:
Cannot insert explicit value for identity column in table 'EnumTest' when IDENTITY_INSERT is set to OFF.
So, how do I write my class so that I'm able to set the value of a Primary Key in EF?
Edit:
I tried adding the following Code-based Migration to set IDENTITY_INSERT to ON:
public override void Up()
{
Sql("SET IDENTITY_INSERT QuoteExtra ON");
}
I ran it and tried again, but got the same exception as above. What's strange is the database does reflect this setting, and running SQL against it directly does allow me to insert arbitrary values in for the primary key - so it would appear Entity Framework itself is enforcing this rule, and neglecting to recognize that IDENTITY_INSERT is not in fact set to off. Do I need to set it somewhere in EF itself?
Edit 2:
I misunderstood IDENTITY_INSERT; I assumed setting it once left it on for that table indefinitely. In fact it lives as long as the "Session," meaning that for example setting it in a Migration means it lives... as long as that Migration runs, and has no bearing on future connections like my later .Add() with EF, which explains why I still got that exception - the DB really is the source of the exception, not EF. Since IDENTITY_INSERT is limited to at most one table per session it's a fairly inefficient way to do this - not creating an Identity PK column in the first place seems like a better route.