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)
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.
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:
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)