I have an MVP app that reads data from a SQL DB using EntityFramework. That data is copied from an external CMS website database, so the data isn’t always reliable.
One of the fields I read is of ‘bit’ datatype in SQL, and is either a 1 or 0, and ASP.NET MVC wants it as a boolean, otherwise I get errors about converting boolean to int.
The problem is sometimes that bit value can be NULL in the DB, and that crashes my MVC app. I can’t check for NULL, because I get errors that the boolean datatype can only be true or false.
Example
Model
namespace Foo.Models
{
[Table("provider")]
public class Bar
{
//can't check for null here, getter and setter only allow boolean
public Boolean FooBar { get; set; }
}
}
Controller
namespace Foo.Controllers
{
public ActionResult BarList()
{
//Can't check for null here, because if(Boolean == null) will always evaluate to false
List<Bar> bars = db.Bar.ToList();
return View(bars);
}
}
If FooBar is ever NULL, an error is thrown in the view that I can’t have a NULL in a boolean. How do I handle this situation?
You can use a generic
Nullable<bool>(can also be expressed asbool?):Then use it as follows: