[英]How to handle exception in empty return data with IEnumerable<decimal> C#
我正在使用 Dapper 並想使用存儲過程返回今天的銷售額,但如果今天沒有銷售,它會返回空值,從而引發異常“'對象引用未設置為對象的實例。” 在與Query
的行。
如何處理那個異常?
使用的代碼
public decimal GetAllSaleTotal(string connectionStringName = "POS")
{
string connectionString = GetConnectionString(connectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
var result = connection.Query<decimal>("dbo.GetTotalSales", commandType:
CommandType.StoredProcedure).First();
return result;
}
}
為什么不使用 try..catch 語句處理異常。
此外,您應該使用var result = connection.Query<decimal?>("dbo.GetTotalSales", commandType: CommandType.StoredProcedure).FirstOrDefault();
這是我可以處理的方法。 使用Take
得到 0 或 1 行,然后檢查長度。
public decimal GetAllSaleTotal(string connectionStringName = "POS")
{
string connectionString = GetConnectionString(connectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
var result = connection.Query<decimal>
(
commandText: "dbo.GetTotalSales",
commandType: CommandType.StoredProcedure
).Take(1).ToList();
return result.Count > 0 ? result[0] : 0M;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.