下面的 C# 代码中使用了 Dapper 的 ReadAsync
entryList.Entries = (await result.ReadAsync<BlogEntry>()).ToList();
如果读不到数据,就会抛异常 Sequence contains no elements
System.InvalidOperationException: Sequence contains no elements
at System.Linq.ThrowHelper.ThrowNoElementsException()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.ThrowZeroRows(Row row) in /_/Dapper/SqlMapper.cs:line 1256
如何用简单的方法避免抛异常并返回空类列表?
下面的代码使用 ToList 可以正常运行
IEnumerable<string> entries = [];
Console.WriteLine(entries.ToList());
将 ToList 改为 First 可以重现问题
IEnumerable<string> entries = [];
Console.WriteLine(entries.First());
是 ReadAsync 时执行 First
方法引起的
汗,弄错了,引发异常的是前面一行代码,即下面第1行代码
entryList.TotalCount = await result.ReadFirstAsync<int>();
entryList.Entries = (await result.ReadAsync<BlogEntry>()).ToList();
存储过程中直接 return
,造成 ReadFirstAsync
引发 "Sequence contains no elements" 异常,改用 ReadFirstOrDefaultAsync
解决了
entryList.TotalCount = await result.ReadFirstOrDefaultAsync<int>();
entryList.Entries = entryList.TotalCount > 0 ?
(await result.ReadAsync<BlogEntry>()).ToList()
: [];