MVC - @Html.CheckBoxFor
我需要一个复选框,但数据库中的基础数据是smallint 类型。不确定如何使用该数据类型创建 @Html.Checkbox。它抱怨说:
无法隐式转换类型“short?” 'bool'
这是我的代码:
@Html.CheckBoxFor(model => model.HasCycle)
I need a checkbox but the underlying data is of type smallint in the database. Not sure how to make the @Html.Checkbox with that datatype. It complains saying the following:
Cannot implicitly convert type 'short?' to 'bool'
Here is the code that I have:
@Html.CheckBoxFor(model => model.HasCycle)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我也遇到了和你一样的问题。我们使用smallint来映射数据库中的布尔值,并且我们无法更改它。
我正在开发一个新的 ASP.NET MVC 应用程序,基于我们现有的数据库,所以我必须处理这个问题。
我采用的解决方案是创建一个未映射的布尔属性,以在我的映射(smallint/short)属性之间进行转换。如下:
效果很好。
I was having the same problem than you. We use smallint to map boolean values in our database, and we cannot change that.
I am developing a new ASP.NET MVC app, based on our existing database, so I have to deal with this issue.
The solution I adopted, was to create a not mapped boolean property to convert from and to my mapped (smallint / short) property. Like follows:
It works fine.
如果要在数据库中存储布尔值,则应使用数据库类型“bit”而不是smallint(其中0为假,1为真)。
否则,您需要首先将 model.HasCycle 转换为 bool。另外,由于它是短类型? (可空),您也需要处理空值。您可能希望在模型本身中处理这个问题,并将模型中的 HasCycle 公开公开为 bool 而不是 Short。尽管如此,您可能会反复遇到一些问题,正确的方法是更改数据库类型。
从短路转换?对于 bool 你可以做类似的事情:
If you are storing a boolean value in the database, then you should use the DB type 'bit' instead of smallint (where 0 will be false and 1 will be true).
Otherwise, you will need to first convert model.HasCycle to a bool. Also, since it is of type short? (nullable), you will need to handle null values too. You will probably want to handle this in the model itself, and publicly expose HasCycle from the model as a bool instead of a short. Still, you may run into some problems going back and forth, and the right way to do it is to change the database type.
To convert from a short? to a bool you can do something like:
复选框是一个布尔值,表示 true 或 false。如果您期望 true/false (1,0),您可能应该将数据库类型设置为 bool。如果您不想这样做,则必须将 int 值转换为 bool (1,0)
a checkbox is a boolean value, meaning true or false. if you are expecting true/false (1,0) you probably should set the database type to a bool. if you don't want to do this, you will have to convert the int value to a bool (1,0)