InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.SByte'.

本文发布于 5 年前,部分内容可能已经失去参考价值。

当 MySQL 中使用 tinyint(1) 作为布尔值类型时,ASP.NET Core DBFirst 创建模型时会将其定义为 sbyte,运行时会抛出异常:

InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.SByte'.

我们可以在数据库连接字符串中加入 TreatTinyAsBoolean=false 来实现不抛出异常,但程序中赋值和判断该字段时还是会比较麻烦。

因此我更倾向于将数据库中该字段类型改为 bit(1)


2019.11.28 注:这回遇到 tinyint(1) 映射到了 C# 的 bool,而 bit(1) 却映射到了 ulong。具体什么原因未作排查,反正哪个最终为 bool 就选哪个吧。

xoyozo 4 年前
转载请注明出处
云服务器 精选特惠
可能相关的内容