将Entity Framework T4模板与系统版本的时态表一起使用

时间:2018-05-21 21:25:26

标签: c# sql-server entity-framework t4 temporal-tables

要解决我的错误(如下所示),我想知道如何编辑我的Entity Framework T4模板,以便将“ HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed)”添加到GENERATED ALWAYS AS ROW START我自动生成的类的POCO配置部分中的Temporal Table的/ END列如下:

Property(x => x.ValidFrom).HasColumnName(@"valid_from").HasColumnType("datetime2").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Property(x => x.ValidTo).HasColumnName(@"valid_to").HasColumnType("datetime2").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

我可以手动添加(解决我的错误),但当我保存T4模板时它被覆盖了。

尝试插入记录时出错: "无法在表' my_table'的GENERATED ALWAYS列中插入显式值。将INSERT与列列表一起使用以排除GENERATED ALWAYS列,或将DEFAULT插入GENERATED ALWAYS列。"

我看过这篇文章,但它没有帮助(可能只有在使用edmx文件时才有效,或者我不理解解决方案):Entity Framework not working with temporal table

我的时间表的例子

CREATE TABLE [dbo].[my_table](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [user_id] [int] NOT NULL,
    [valid_from] [datetime2](7) GENERATED ALWAYS AS ROW START NOT NULL,
    [valid_to] [datetime2](7) GENERATED ALWAYS AS ROW END NOT NULL,
 CONSTRAINT [PK_my_table] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
    PERIOD FOR SYSTEM_TIME ([valid_from], [valid_to])
) ON [PRIMARY]
WITH
(
SYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[my_table_history] )
)
GO
ALTER TABLE [dbo].[my_table] ADD  CONSTRAINT [DF_my_table_SysStart]  DEFAULT (sysutcdatetime()) FOR [valid_from]
GO
ALTER TABLE [dbo].[my_table] ADD  CONSTRAINT [DF_my_table_SysEnd]  DEFAULT (CONVERT([datetime2](7),'9999-12-31 23:59:59')) FOR [valid_to]
GO

插入记录的示例代码

var recordToCreate = new MyTable()
{
    UserId = info.UserId,
    ValidFrom = info.ValidFrom,
    ValidTo = info.ValidTo,
};
_context.MyTables.Add(recordToCreate);
_context.SaveChanges();

1 个答案:

答案 0 :(得分:0)

我明白了。我必须编辑EF.Reverse.POCO.Core.ttinclude文件,将“IsGeneratedAlwaysType”添加到许多类,方法和SQL查询中。我基本上把它添加到了我发现'IsForeignKey'的地方。我粘贴在我添加到每个部分的片段下面。

public class Column
{
    public bool IsGeneratedAlwaysType;
    private void SetupConfig()
    {
        else if (IsGeneratedAlwaysType)
        {
            if(Settings.UseDataAnnotations)
                DataAnnotations.Add("DatabaseGenerated(DatabaseGeneratedOption.Computed)");
            else
                databaseGeneratedOption = string.Format(".HasDatabaseGeneratedOption({0}DatabaseGeneratedOption.Computed)", schemaReference);
        }
    private static Column CreateColumn(IDataRecord rdr, Regex rxClean, Table table, Regex columnFilterExclude)
    { 
        var col = new Column
        {
            IsGeneratedAlwaysType = rdr["IsGeneratedAlwaysType"].ToString().Trim().ToLower() == "true",
private class SqlServerSchemaReader : SchemaReader
{
    private const string TableSQL = @"
    CAST(CASE WHEN COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'GeneratedAlwaysType') > 0 THEN 1
         ELSE 0
       END AS BIT) AS IsGeneratedAlwaysType
    FROM    #Columns c
private const string SynonymTableSQLSetup = @"
        CAST(CASE WHEN COLUMNPROPERTY(OBJECT_ID(QUOTENAME(sc.NAME) + '.' + QUOTENAME(o.NAME)), c.NAME, 'GeneratedAlwaysType') > 0 THEN 1
                  ELSE 0
             END AS BIT) AS IsGeneratedAlwaysType
        INTO    #SynonymDetails
        FROM    sys.synonyms sn
INSERT INTO #SynonymDetails (SchemaName, TableName, TableType, Ordinal, ColumnName, IsNullable, TypeName, [MaxLength], [Precision],
                            [Default], DateTimePrecision, Scale, IsIdentity, IsStoreGenerated, PrimaryKey, PrimaryKeyOrdinal, IsForeignKey, IsGeneratedAlwaysType)
CAST(CASE WHEN COLUMNPROPERTY(st.base_object_id, c.NAME, ''GeneratedAlwaysType'') > 0 THEN 1
                ELSE 0
            END AS BIT) AS IsGeneratedAlwaysType
FROM    #SynonymTargets st
    INNER JOIN sys.columns c
        private const string SynonymTableSQL = @"
SELECT SchemaName, TableName, TableType, Ordinal, ColumnName, IsNullable, TypeName, [MaxLength], [Precision],
    [Default], DateTimePrecision, Scale, IsIdentity, IsStoreGenerated, PrimaryKey, PrimaryKeyOrdinal, IsForeignKey, IsGeneratedAlwaysType FROM #SynonymDetails";
        private const string TableSQLCE = @"
0 as IsGeneratedAlwaysType
FROM    INFORMATION_SCHEMA.COLUMNS c