如果我想使用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
时未设置为对象实例的对象引用:
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
答案 0 :(得分:0)
好吧,Where
和Select
没有任何意义,如果它是一个int。很确定你想要删除它们。
conn.Query<int>("select 123 where 1=0")
.ToArray();
当你这样做时,你有什么问题吗?
答案 1 :(得分:0)
我的问题原来是我在代码中执行了LEFT JOIN
,但是当我尝试重现错误时我使用了INNER JOIN
,所以,我无法重现行为。使用LEFT JOIN
,返回了值为NULL
的单行,这就是我在NULL
和int
之间收到投射错误的原因。