I'm using database first entity framework 6. After changing some of the tables in my schema to be temporal tables, I started getting the following error when attempting to insert new data:
Cannot insert an explicit value into a GENERATED ALWAYS column in table '<MyDatabase>.dbo.<MyTableName>. Use INSERT with a column list to exclude the GENERATED ALWAYS column, or insert a DEFAULT into GENERATED ALWAYS column.
It looks like EF is trying to update the values of the PERIOD
columns which are managed by the system.
Removing the columns from the EDMX file seems to correct the problem, but this is not a viable solution since the columns are re-added each time the model is regenerated from the database.
There are two solutions to this problem:
StoreGeneratedPattern
on thePERIOD
columns (ValidFrom and ValidTo in my case) to be eitheridentity
orcomputed
. Identity is probably better since computed will cause EF to refresh the values on an Insert and Update as opposed to just an insert withidentity
IDbCommandTreeInterceptor
implementation to remove the period columns. This is my preferred solution since it requires no additional work when adding new tables to the model.Here's my implementation:
Register this interceptor with EF by running the following anywhere in your code before you use your context:
Making the Period start column and Period end column should fix this issue. We can do this by
We can see the settings for hidden against these columns in the sys.columns table
An other solution is create default constraint in the fields of the table.
In the code not need alteration nothing.