c# - 在 Entity Framework Core 上转换为 ulong 的 SqlLite 中正确的 RowVersion 模拟

标签 c# sqlite entity-framework-core database-concurrency rowversion

我试图通过对 rowversion 列的简单查询使 RowVersion 在 SqlLite 和 SqlServer 上都能正常工作。为了能够做到这一点,我需要将 rowversion 列转换为 ulong 而不是 byte[] 并且仍然可以正常工作。

public abstract class VersionEntity
{
    public ulong RowVersion { get; set; }
}

public class Observation : VersionEntity
{
    public Guid Id { get; set; }
    public Guid TaskId { get; set; }
    public string Description { get; set; }
    public DateTime DueDate { get; set; }
    public Severity Severity { get; set; }
}

public class TestDbContext : DbContext
{
    public static string ConnectionString { get; set; } = "Data Source=dummy.db";
    public DbSet<Observation> Observation { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
         modelBuilder.Entity<Observation>().HasKey(o => o.Id);
         modelBuilder.Entity<Observation>().Property(o => o.RowVersion).HasConversion(new NumberToBytesConverter<ulong>()).IsRowVersion();
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite(ConnectionString);
        optionsBuilder.UseLazyLoadingProxies();
    }

}

在我的第一次添加迁移中,将 RowVersion 更改为具有 rowVersion: true(未自动添加)。
还添加了
private string _triggerQuery = @"CREATE TRIGGER Set{0}RowVersion{1}
   AFTER {1} ON {0}
   BEGIN
      UPDATE {0}
      SET RowVersion = current_timestamp
      WHERE rowid = NEW.rowid;
   END
";

migrationBuilder.Sql(String.Format(_triggerQuery, tableName, "UPDATE"));
migrationBuilder.Sql(String.Format(_triggerQuery, tableName, "INSERT"));

这样它就用触发器创建来模拟 SqlServer RowVersion 增量全局值。

迁移工作,先保存工作
context.Database.Migrate();
var id = Guid.NewGuid();
context.Observation.Add(new Observation
{
    Id = id,
    Description = "Test description1",
    TaskId = Guid.NewGuid(),
    Severity = Severity.Low,
    DueDate = DateTime.Now
});
context.Observation.Add(new Observation
{
    Id = Guid.NewGuid(),
    Description = "Test description2",
    TaskId = Guid.NewGuid(),
    Severity = Severity.Low,
    DueDate = DateTime.Now
});
context.SaveChanges(); // This works, and saves data
var observation = context.Observation.FirstOrDefault(o => o.Id == id);
observation.Description = "changed.."; // Checking here will show a value on RowVersion property
context.SaveChanges(); // This fail with concurrency error

并发错误:数据库操作预期影响 1 行,但实际影响 0 行。自加载实体以来,数据可能已被修改或删除。见 http://go.microsoft.com/fwlink/?LinkId=527962有关理解和处理乐观并发异常的信息。

我不明白为什么这应该是一个问题。任何人都知道为什么这不起作用?获取的实体似乎在 RowVersion 属性上有一个值。但是当它被保存时,它认为它已经改变了。

最佳答案

我放弃了尝试将 IsRowVersion 与 Sqlite 一起使用。

最终将 RowVersion 的类型设置为 long,并使用 IsConcurrencyToken().ValueGeneratedOnAddOrUpdate().HasDefaultValue(0);而不是 IsRowVersion().HasConversion(..)

也使用 julianday 而不是 current_timestamp

private static string _triggerQuery = @"CREATE TRIGGER Set{0}RowVersion{1}
        AFTER {1} ON {0}
        BEGIN
            UPDATE {0}
            SET RowVersion = CAST(ROUND((julianday('now') - 2440587.5)*86400000) AS INT)
            WHERE rowid = NEW.rowid;
        END
    ";

migrationBuilder.Sql(String.Format(_triggerQuery, tableName, "UPDATE"));
migrationBuilder.Sql(String.Format(_triggerQuery, tableName, "INSERT"));

现在它可以正常工作,并且可以降低到毫秒以进行更改。通过这种方式,还可以轻松查询某个时间点之后的所有更改。

关于c# - 在 Entity Framework Core 上转换为 ulong 的 SqlLite 中正确的 RowVersion 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58448268/

相关文章:

执行 File.Copy 时出现 C# unauthorizedAccessException

c# - 制作一个随机整数数组

java - SQLite 数据库中第 71 行的 NullPointerException

iphone - 数据存储在plist数据库好还是Sqlite数据库好?

c# - 不支持从 _ 到 _ 的关系,因为拥有的实体类型 _ 不能位于非所有权关系的主体端

c# - 何时在 ASP.NET Core 5 中处理 DbContext 实例

c# - 如何在 Entity Framework Core 2.0 中的模型本身内部使用 OnModelCreating?

c# - 如何在java中重新初始化int数组

c# - 获取@Html.DropDownList选定的值

sql - 只列出重复的名字