
[英]Store update, insert, or delete statement affected an unexpected number of rows
[英]LINQ to SQLite Cannot Update: “Store update, insert, or delete statement affected an unexpected number of rows”
使用 System.Data.SQLite 和 LINQ to Entities,我无法进行简单的更新。
这段代码
using (Entities context = new Entities()) {
var Obj = context.MyTable.Where(m => m.Title.StartsWith("Alaska")).FirstOrDefault();
Obj.Artist = "A";
context.SaveChanges();
}
抛出这个异常
A first chance exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll
Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
我怎样才能解决这个问题?
我在一个孤立的测试项目中,所以没有其他事情发生。
该数据库是从 SQL Server 数据库自动转换而来的,结果证明 SQLite 不支持 UNIQUEIDENTIFIER 数据类型,但该表仍将列和主键定义为 UNIQUEIDENTIFIER。 每当我更新具有 UNIQUEIDENTIFIER 键的表时,我都会收到此错误。 使用 INT 键更新表时,没问题。
解决方案是将这些列的数据类型更改为 TEXT。 然后在 .NET 映射类中,数据类型从 Guid 更改为 String,因此我不得不相应地调整代码,但现在它可以工作了。
我们在尝试使用 SaveChanges() 时可能会遇到同样的问题。 就我而言,我使用了 Attach()-SaveChanges() 组合来执行更新。 我正在使用 SQLite DB 及其 EF 提供程序(相同的代码在 SQLServer DB 中没有问题)。
我发现,当您的 DB 列在 SQLite 中具有 GUID(或 UniqueIdentity)并且您的模型是 nvarchar 时,SQLIte EF 默认将其视为 Binary(即 byte[])。 因此,当 SQLite EF 提供程序尝试将 GUID 转换为模型(在我的情况下为字符串)时,它将失败,因为它将转换为字节 []。 修复方法是通过定义“BinaryGUID=false;”告诉 SQLite EF 将 GUID 视为文本(因此转换为字符串,而不是字节 [])。 在连接字符串(或元数据,如果您首先使用数据库)中,如下所示:
<connectionStrings>
<add name="Entities" connectionString="metadata=res://savetyping...=System.Data.SQLite.EF6;provider connection string="data source=C:\...\db.sqlite3;Version=3;BinaryGUID=false;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
链接到对我有用的解决方案: SQLite Entity Framework 6 provider 如何处理 Guids?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.