Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Dapper handle nullable boolean/bit fields? [INVALID]

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.

like image 353
NickG Avatar asked Jul 07 '14 09:07

NickG


1 Answers

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; }
}
like image 196
Marc Gravell Avatar answered Sep 20 '22 01:09

Marc Gravell