如何让Dapper将int映射到布尔属性?

16

我有这个类...

public class MyDTO
{
    public int Id { get; set; }

    public bool Selected { get; set; }
}

然后使用 Dapper 尝试创建类似这样的列表...

            var list = this.db.OpenConnection().Query<MyDTO>(
            @"SELECT T1.id, T2.id IS NOT NULL AS selected
            FROM     table1 T1
            LEFT
            JOIN     table2 T2 
            ON   T2.id = T1.id
            AND  Tl.id = @Id",
            new { Id = id });

该函数返回一个类似于以下结果集的结果...

id  selected
 9         0
10         1
11         1
12         0

但是当执行以上代码时,我会收到一个错误。

[InvalidCastException: Specified cast is not valid.]
Deserialize3d3c9260-abcb-4964-97c1-4a4e66b786d3(IDataReader ) +354

[DataException: Error parsing column 2 (selected=0 - Int64)]
Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader) in     C:\Projects\Web\SqlMapper.cs:1685
Deserialize3d3c9260-abcb-4964-97c1-4a4e66b786d3(IDataReader ) +432
Dapper.<QueryInternal>d__13`1.MoveNext() in C:\Projects\Web\Source\SqlMapper.cs:608
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +327
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\Projects\Web\Source\SqlMapper.cs:538

我现在打算创建一个“Translating”属性,但这是一个不寻常的用例吗?


1
你的表长什么样子,你运行的是哪个操作系统版本?我在我的系统上测试了上述代码,并且使用Dapper可以将int值映射到布尔值而没有任何问题。 - Alex
1个回答

20

我不确定这是否是最好的方法,但它应该能解决问题:

SELECT T1.id, CAST(CASE WHEN T2.id IS NULL THEN 0 ELSE 1 END AS BIT) AS selected
FROM ...

说实话,我并不确定你的T2.id IS NOT NULL AS selected子句在第一次使用时是否为合法的T-SQL语句,但如果你说它有效,我会相信你的!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接