尝试从 SQLite 获取记录时发生非常简单的故障
System.InvalidCastException = "Specified cast is not valid."
这就是我收到的错误。
我的代码非常简单:
public Staff FindStaff(int id)
{
try
{
return db.Staffs.SingleOrDefault(c => c.ID == id);
}
catch (Exception e)
{
Debug.WriteLine(e.InnerException);
throw;
}
}
我使用断点来检查“id”参数在执行时的值,并且它具有现有记录的数值。例如,4。
错误在 return 语句上触发。
奇怪的是,我的项目中的另一个实体有完全相同类型的代码,并且工作正常。什么可能导致此错误?
这是我用来创建表的 TSQL。工作人员是导致错误的人,学生工作 100% 正常。
create table Student
(
ID integer primary key autoincrement,
...other fields...
);
create table Staff
(
ID integer primary key autoincrement,
IDStaffType integer references StaffType(ID),
...other fields...
);
正如您所看到的,两个 ID 字段都是整数,为什么会引发转换异常?
System.InvalidCastException = "Specified cast is not valid."
That's the error I'm getting.
My code is simple enough:
public Staff FindStaff(int id)
{
try
{
return db.Staffs.SingleOrDefault(c => c.ID == id);
}
catch (Exception e)
{
Debug.WriteLine(e.InnerException);
throw;
}
}
I have used a breakpoint to check what value the 'id' parameter has on execution, and it has a numerical value of an existing record. For example, 4.
The error fires on the return statement.
What's weird is I have the exact same type of code for another entity on my project and it works fine. What could be causing this error?
Here's the TSQL I used to create the tables. Staff is the one that is causing the error, Student works 100% fine.
create table Student
(
ID integer primary key autoincrement,
...other fields...
);
create table Staff
(
ID integer primary key autoincrement,
IDStaffType integer references StaffType(ID),
...other fields...
);
As you can see, both ID fields are integers, why would a conversion exception fire?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 SQLite 中,“integer”是 64 位 int,在 C# 中是
long
。但我怀疑这不是问题。 SQLite 不强制执行数据类型(除了
整数主键
列),因此完全有可能您的记录中存储有存储在整数列中的字符串。这可以解释有时有效但有时无效的奇怪行为(只有问题记录才会导致错误)。在我自己遇到这种情况后,我更改了我的 edmx 文件以始终将 SQLite 数据视为字符串,例如,
与
中定义的匹配插入/更新/删除“存储过程” 的
。DefiningQuery
存储模型In SQLite, "integer" is a 64-bit int, which is a
long
in C#.I suspect that's not the problem, though. SQLite does not enforce data types (except for
integer primary key
columns), so it's entirely possible that you have a record that has, say, a string stored in an integer column. This would explain the strange behavior where it sometimes works but sometimes does not (only the problem record would cause errors).After running into this scenario myself, I've changed my edmx file to always treat SQLite data as strings, e.g., a
DefiningQuery
ofwith matching Insert/Update/Delete "stored procedures" defined in
StorageModels
.