[英]How do I get a nullable int[] with dapper?
如果我想使用Dapper獲取包含單個int
列的一堆行,則此結果集可能為空。 使用Dapper查詢此數據的最佳方法是什么?
例如,如果我有以下方法返回我想要的:
public void int[] GetInts()
{
conn.Query<int?>("select 123 where 1=1")
.Where(x=> x.HasValue)
.Select(x => x.Value)
.ToArray();
}
如果我將行更改為:
conn.Query<int>("select 123 where 1=0").ToArray();
沒有結果時,我收到了一個轉換錯誤。
堆棧跟蹤在下面,並且異常只是(T)next
轉換(T)next
時未設置為對象實例的對象引用:
at Dapper.SqlMapper.<QueryInternal>d__13`1.MoveNext() in .\SqlMapper.cs:line 611
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in .\SqlMapper.cs:line 539
好吧, Where
和Select
沒有任何意義,如果它是一個int。 很確定你想要刪除它們。
conn.Query<int>("select 123 where 1=0")
.ToArray();
你這樣做有什么問題嗎?
我的問題原來是我在代碼中進行LEFT JOIN
,但是當我嘗試重現錯誤時我正在使用INNER JOIN
,所以,我無法重現相同的行為。 使用LEFT JOIN
,返回值為NULL
的單行,這就是我在NULL
和int
之間得到轉換錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.