如何讓dapper將int映射到布爾屬性

.net dapper

我有這堂課......

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

我現在要創建一個“翻譯”屬性,但這是一個不尋常的用例嗎?

一般承認的答案

我不確定這是否是最好的方法,但它應該做到這一點:

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,但是如果你說它正在運行那麼我會接受你的話!)



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因