I am using fluent Hibernate in C# to query a sqlite-database.
So this code works fine when there is at least one CashTransaction in my database.
public decimal? GetSum(ISession dbSession)
{
var transactions = dbSession.Query<CashTransaction>();
Debug.WriteLine(transactions.Count().ToString());
return transactions.Sum(s => s.Value);
}
But if the CashTransaction table is empty, an InvalidOperationException is thrown in the last line. Why is this?
I could change my code to:
public decimal? GetSum(ISession dbSession)
{
var transactions = dbSession.Query<CashTransaction>();
if (transactions.Count() > 0)
{
return transactions.Sum(s => s.Value);
}
else
{
return 0;
}
}
but this seems not very elegant.
CodePudding user response:
Ok, it seems like this code here works also with an empty CashTransaction table:
public decimal? GetSum(ISession dbSession)
{
var transactions = dbSession.Query<CashTransaction>();
return transactions.Sum(s => (decimal?)s.Value);
}
The reason for this behavior seems to be differences in SQL and linq where it was decided to prefere the linq way. At least this is how its explained here https://social.msdn.microsoft.com/Forums/office/en-US/479f2823-c942-4990-adca-21e03f969a12/sum-on-empty-table-throws-invalidoperationexception