简体   繁体   English

Dapper可以处理可空的布尔/位字段吗? [无效]

[英]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. 我第一次尝试使用Dapper,但是我立刻遇到了问题,因为似乎Dapper似乎不能处理可空字段。 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: 如果我的SQL Server数据库中有一个可以为空的布尔字段并尝试使用Dapper来填充我的C#类上的可空布尔属性,则如果布尔字段包含空值,则抛出异常:

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. 我发现很难相信Dapper无法处理它,因为它看起来已经存在了一段时间,这是一个非常基本的功能。

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. 我的专栏实际上是一个nvarchar,碰巧包含0或1,因此我没有注意到。 Changing it to BIT (or the C# property to "string?") fixes the problem. 将它更改为BIT(或将C#属性更改为“string?”)可以解决问题。

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; }
}

Since Dapper does not make too much plumbing, the recordset coming from the database contains a string, a stated by the error. 由于Dapper没有做太多的管道,来自数据库的记录集包含一个字符串,由错误说明。 Try to check the column type, and when it is clear you can change the DTO class accordingly, or cast it in some way in the query. 尝试检查列类型,当它清楚时,您可以相应地更改DTO类,或者在查询中以某种方式转换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM