【问题标题】:EF Core Timestamp error when running SqlLite Integration Tests运行 SqlLite 集成测试时出现 EF Core 时间戳错误
【发布时间】:2020-01-24 00:42:22
【问题描述】:

根据这篇文章:https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite,我正在尝试使用 Sqlite 提供程序进行测试。 (在内存中工作正常)。我的专栏之一是时间戳专栏:

[Timestamp]
public byte[] Timestamp { get; set; }

在使用 options.UseSqlServer() 时效果很好。但是,当我使用此配置运行测试时:

_connection = new SqliteConnection("DataSource=:memory:");   
_connection.Open();

_options = new DbContextOptionsBuilder<BuyGroupDataContext>()
     .UseSqlite(_connection)                                          
     .Options;

...
var bg = GenerateGroup();
bg.Timestamp = Encoding.ASCII.GetBytes(DateTime.Now.ToString());

using (var context = new GroupDataContext(_options))
{
    context.Groups.Add(bg);
    context.SaveChanges(); // fails here
}

错误:

Microsoft.EntityFrameworkCore.DbUpdateException:发生错误 在更新条目时。有关详细信息,请参阅内部异常。 ---- Microsoft.Data.Sqlite.SqliteException:SQLite 错误 19:'NOT NULL 约束失败:Group.Timestamp'。

【问题讨论】:

  • sql中Group.Timestamp是什么数据类型?调试并检查是否有值。 Not Null 引发异常。
  • (时间戳,非空)

标签: c# .net entity-framework


【解决方案1】:

我怀疑您使用 Timestamp 进行行版本控制是否正确?如果您处于最佳并发状态,请不要忘记配置您的实体,例如:

public void Configure(EntityTypeBuilder<T> builder)
{
    builder.Property(prop => prop.Timestamp).IsRowVersion();
{

查看更多Here

【讨论】:

  • 没用。在 Timestamp 字段中应该填充什么以进行测试?
【解决方案2】:

通过添加解决了我的问题:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...

    modelBuilder.Entity<Entities.BuyGroup>().Property(o => o.Timestamp)
        .IsRowVersion()
        .HasDefaultValueSql("CURRENT_TIMESTAMP");

    base.OnModelCreating(modelBuilder);
}

到我的 DataContext 类的 OnModelCreating 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 2021-05-06
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多