【发布时间】:2021-10-31 13:09:38
【问题描述】:
我使用 EntityFramework SQLite 并遇到了奇怪的错误。我搜索了类似的问题,但没有适合我的解决方案。
在我的实际项目中它根本不起作用。 (有同样的例外)在我第一次执行代码时它工作正常(刚刚创建数据库时)的示例中,当我再次运行它时出现异常:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.'
可在here找到最小可重复样本。
代码比较简单:
using (var ctx = new SqliteDbContext("data.db"))
{
ctx.Database.Migrate();
ctx.UserReferencesData.Add(new UserReferencesData()
{
ColumnId = Guid.NewGuid(),
MetadataId = -2,
RowId = 1,
ColumnType = 1,
StringValue = "asdf",
});
ctx.SaveChanges();
}
模型也相当简单,但我怀疑它与特定的列或索引有关,因为其他表工作正常:
[Table("UserReferencesData")]
[Index(nameof(RowId))]
public class UserReferencesData
{
[Key]
public int Id
{
get;
set;
}
public int MetadataId
{
get;
set;
}
public int RowId
{
get;
set;
}
public Guid ColumnId
{
get;
set;
}
public int ColumnType
{
get;
set;
}
//type 0
public DateTime? DateValue
{
get;
set;
}
//type 1
public string StringValue
{
get;
set;
}
//type 2
public int? IntValue
{
get;
set;
}
//type 3
public double? DoubleValue
{
get;
set;
}
//type 4
public bool? BoolValue
{
get;
set;
}
//type 5
public decimal? DecimalValue
{
get;
set;
}
}
数据库上下文:
public class SqliteDbContext : DbContext
{
private string _dbPath = @"data.db";
public SqliteDbContext(string dbPath)
{
_dbPath = dbPath;
}
//ctor for migration
public SqliteDbContext(DbContextOptions<SqliteDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var path = $"Data Source=\"{_dbPath}\"";
optionsBuilder.UseSqlite(path);//
#if DEBUG
optionsBuilder.EnableSensitiveDataLogging(true);
optionsBuilder.LogTo(s=>System.Diagnostics.Debug.WriteLine(s));
#endif
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserReferencesData>()
.HasOne<UserReferencesMetadata>()
.WithMany()
.HasForeignKey(d => d.MetadataId);
}
public virtual DbSet<UserReferencesData> UserReferencesData
{
get;
set;
}
public virtual DbSet<UserReferencesMetadata> UserReferencesMetadata
{
get;
set;
}
}
当我在 SQLite db 浏览器中执行插入查询时,添加了行。但第二个返回 0 行(我记录了实体框架使用的查询):
INSERT INTO "UserReferencesData" ("BoolValue", "ColumnId", "ColumnType", "DateValue", "DecimalValue", "DoubleValue", "IntValue", "MetadataId", "RowId", "StringValue")
VALUES (null, 'c6c653c5-3fd3-4c54-ae0d-d5565b3cb725', '1', null, null, null, null, '-2', '1', 'asdf');
SELECT "Id"
FROM "UserReferencesData"
WHERE changes() = 1 AND "rowid" = last_insert_rowid();
如果我切换到不同的表,然后再次执行第二个查询,它会弹出一个 id 列表。
【问题讨论】:
标签: sqlite entity-framework-core