SQLite 内存数据库使用临时表测试 EF Core 应用程序

SQLite in-memory databases testing an EF Core application with temporal tables

我们在 Entity Framework 核心应用程序中使用系统版本控制的时间 table。这非常有效,但我们在创建测试时遇到了问题。

https://docs.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables?view=sql-server-ver15

我一直在按照本指南使用 SQLite 内存数据库测试 Microsoft 的 EF Core 应用程序。

https://docs.microsoft.com/en-us/ef/core/testing/sqlite#using-sqlite-in-memory-databases

问题是 Sqlite 会为 SysStartTime 抛出异常。这是预期的,因为 属性 在 DbContext 中被标记为 prop.ValueGenerated = Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.OnAddOrUpdate; 并且通常由 Sql 服务器处理。有没有办法在 SQLite 中完成这项工作?

SqliteException: SQLite Error 19: 'NOT NULL constraint failed: User.SysStartTime'.

用户:

public class User : IEntity
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTime SysStartTime { get; set; }

    public DateTime SysEndTime { get; set; }

    [Required]
    public string ExternalId { get; set; }
}

x单元测试:

public class QuestionUpdateTest: IDisposable
{
    private readonly DbConnection _connection;
    private readonly ApplicationDbContext _context = null;
        
    public ChoiceSequencingQuestionUpdateTest()
    {
        var dbContextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
                        .UseSqlite(CreateInMemoryDatabase())
                        .Options;
                        
        _connection = RelationalOptionsExtension.Extract(dbContextOptions).Connection;

        _context = new ApplicationDbContext(dbContextOptions);
        
        _context.User.Add(new User()
        {
            ExternalId = "1"
        });

        _context.SaveChangesNoUser();
    }
    
    private static DbConnection CreateInMemoryDatabase()
    {
        var connection = new SqliteConnection("Filename=:memory:");

        connection.Open();

        return connection;
    }

    public void Dispose() => _connection.Dispose();
    
    [Fact]
    public void Test2()
    {
        
    }
}

ApplicationDbContext:

public int SaveChangesNoUser()
{
    //Wont help since the property is marked as ValueGenerated
    foreach (var changedEntity in ChangeTracker.Entries())
    {
        if (changedEntity.Entity is IEntity entity)
        {
            switch (changedEntity.State)
            {
                case EntityState.Added:
                    entity.SysStartTime = DateTime.Now;
                    break;
            }
        }
    }

    return base.SaveChanges();
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(string)))
    {
        if (property.GetMaxLength() == null)
            property.SetMaxLength(256);
    }

    foreach (var property in modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetProperties())
        .Where(p => p.ClrType == typeof(DateTime)))
    {
        property.SetColumnType("datetime2(0)");
    }

    foreach (var et in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in et.GetProperties())
        {
            if (prop.Name == "SysStartTime" || prop.Name == "SysEndTime")
            {
                prop.ValueGenerated = Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.OnAddOrUpdate;
            }
        }
    }

    base.OnModelCreating(modelBuilder);
}

迁移:

public partial class Temporaltablesforallentities : Migration
{
    List<string> tablesToUpdate = new List<string>
        {
           "User",
        };

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        foreach (var table in tablesToUpdate)
        {
            string alterStatement = $@"ALTER TABLE [{table}] 
                ADD PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])";
            migrationBuilder.Sql(alterStatement);
            alterStatement = $@"ALTER TABLE [{table}] 
                SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = History.[{table}], DATA_CONSISTENCY_CHECK = ON));";
            migrationBuilder.Sql(alterStatement);
        }
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        foreach (var table in tablesToUpdate)
        {
            string alterStatement = $@"ALTER TABLE [{table}] SET (SYSTEM_VERSIONING = OFF);";
            migrationBuilder.Sql(alterStatement);
            alterStatement = $@"ALTER TABLE [{table}] DROP PERIOD FOR SYSTEM_TIME";
            migrationBuilder.Sql(alterStatement);
            alterStatement = $@"DROP TABLE History.[{table}]";
            migrationBuilder.Sql(alterStatement);
        }
    }
}

https://docs.microsoft.com/en-us/sql/relational-databases/tables/creating-a-system-versioned-temporal-table?view=sql-server-ver15#important-remarks-4

protected override void OnModelCreating(ModelBuilder modelBuilder)中这样解决了:

foreach (var et in modelBuilder.Model.GetEntityTypes())
{
    foreach (var prop in et.GetProperties())
    {
        if (prop.Name == "SysStartTime" || prop.Name == "SysEndTime")
        {
            if (Database.IsSqlServer())
            {
                prop.ValueGenerated = Microsoft.EntityFrameworkCore.Metadata.ValueGenerated.OnAddOrUpdate;
            }
            else
            {
                prop.SetDefaultValue(DateTime.Now);
            }

        }
    }
}

尝试从模型中删除 SysStartTime 和 SysEndTime。您可以使用以下代码段添加它们:

创建一个 Constants.cs 或类似的:

        public const string AddSystemVersioningFormatString = @"
            ALTER TABLE [dbo].[{0}] 
            ADD SysStartTime datetime2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL 
                CONSTRAINT DF_{0}_SysStartTime DEFAULT SYSUTCDATETIME(),
                SysEndTime datetime2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL 
                CONSTRAINT DF_{0}_SysEndTime DEFAULT CONVERT(datetime2, '9999-12-31 23:59:59.9999999'),
                PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)
            ALTER TABLE [dbo].[{0}] 
            SET (SYSTEM_VERSIONING = ON (
                HISTORY_TABLE = [dbo].[{0}History],
                DATA_CONSISTENCY_CHECK = ON )
        )";
        public const string RemoveSystemVersioningFormatString = @"
            ALTER TABLE [dbo].[{0}] SET (SYSTEM_VERSIONING = OFF)
            ALTER TABLE [dbo].[{0}] DROP PERIOD FOR SYSTEM_TIME
            ALTER TABLE [dbo].[{0}] DROP CONSTRAINT DF_{0}_SysStartTime
            ALTER TABLE [dbo].[{0}] DROP CONSTRAINT DF_{0}_SysEndTime
            ALTER TABLE [dbo].[{0}] DROP COLUMN SysStartTime, SysEndTime
            DROP TABLE IF EXISTS [dbo].[{0}History]
        ";

然后在您的迁移中:

migrationBuilder.Sql(string.Format(Constants.AddSystemVersioningFormatString, "User"));

因此您的模型不会知道额外的列,并且您不必在 EF 中显式设置任何内容,因为 SQL 服务器会为您处理所有设置。