Entity Framework not working with temporal table

后端 未结 5 1848
北海茫月
北海茫月 2020-12-03 07:37

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

5条回答
  •  星月不相逢
    2020-12-03 08:19

    I did manage to use temporal table with entities framework without any overhead.

    1. Use the default constraint, as José Ricardo Garcia says

      An other solution is create default constraint in the fields of the table.

      • Heres the script for altering table instead of creating table.

        ALTER TABLE [dbo].[Table]
        ADD ValidFrom DATETIME2(0) GENERATED ALWAYS AS ROW START HIDDEN CONSTRAINT [Df_Table_ValidFrom] DEFAULT DATEADD(SECOND, -1, SYSUTCDATETIME()),
        ValidTo   DATETIME2(0) GENERATED ALWAYS AS ROW END HIDDEN CONSTRAINT [Df_Table_ValidTo] DEFAULT '9999.12.31 23:59:59.99',
        PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
        go
        ALTER TABLE [dbo].[Table]
        SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE=dbo.[TableHistory]))
        GO
        
    2. Switch column to identity in edmx, as Matt Ruwe says

      In the property window for the column in the EDMX designer, change the StoreGeneratedPattern on the PERIOD columns (ValidFrom and ValidTo in my case) to be identity. Identity is better than computed since computed will cause EF to refresh the values on an Insert and Update as opposed to just an insert with identity

    3. Since the two method above are working just fine for insert, they didnt work for updating the entities. I had to manually tell that the two column were not modified,

      Entry(existingResult).CurrentValues.SetValues(table);
      Entry(existingResult).Property(x => x.ValidTo).IsModified = false;
      Entry(existingResult).Property(x => x.ValidFrom).IsModified = false;
      

    now i can succesffuly call db.SaveChanges() and get rid of the error, even if the entities has been modified. Hope it help! Note: I using DbFirst and EF6

提交回复
热议问题