Working with .NET Boolean and Oracle along with ASP.NET MVC

Somethings that are straight forward in MS-SQL and .NET are bit convoluted when using Oracle and .NET. A good example for this case is when trying to map a database Boolean field to a .NET POCO. With MS-SQL we can straight away use bit which has a possible values of 1 or ``, but with Oracle since it does not have a built in Boolean type we would normally go with a single character field with a value of 'Y' or 'N'.

This is not a big issue when we are working only on the database side or if we are using pre-MVC ADO.NET based mapping mechanism. But with using ASP.NET MVC we normally use an ORM (like Dapper) and pass in a POCO to get the native representation of the data in .NET. Since Oracle’s 'Y' or 'N' cannot be directly mapped to a .NET’s System.Boolean we need a workaround for this issue. Secondly you cannot directly use the @Html.CheckBoxFor(m => m.DBFlag) as that would throw up the following error Cannot implicitly convert type 'char' to 'bool'

A simple workaround that I use is to have a wrapper property for the original property which handles the conversion dynamically.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class MyActionModel {
	public char DBFlag  {get; set;} // POCO property representing the actual column in the database
	
	public bool MyFlag { // Wrapper property that works around the Boolean issue
		get {
			return DBFlag == 'Y';
		}
		set {
			DBFlag = value ? 'Y' : 'N';
		}
	}
}

now we can happily use @Html.CheckBoxFor(m => m.MyFlag).

comments powered by Disqus