I'm trying to use Dapper for the first time, but I've immediately run into the problem in that it doesn't seem that Dapper can handle nullable fields. This surprises me greatly as these are extremely common.
If I have a nullable boolean field in my SQL Server database and try and use Dapper to populate the nullable boolean property on my C# class, an exception is thrown if the boolean field contains a null value:
System.FormatException: String was not recognized as a valid Boolean.
Is there any fix or workaround for this? I find it hard to believe Dapper can't handle this as it looks like it's been around for a while and this is an extremely basic function.
EDIT: This was my mistake! My column was actually a nvarchar which happened to contain 0 or 1, and as such, I hadn't noticed. Changing it to BIT (or the C# property to "string?") fixes the problem.
Yep, works just fine:
public void SO24607639_NullableBools()
{
var obj = connection.Query<HazBools>(
@"declare @vals table (A bit null, B bit null, C bit null);
insert @vals (A,B,C) values (1,0,null);
select * from @vals").Single();
obj.IsNotNull();
obj.A.Value.IsEqualTo(true);
obj.B.Value.IsEqualTo(false);
obj.C.IsNull();
}
class HazBools
{
public bool? A { get; set; }
public bool? B { get; set; }
public bool? C { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With