Why do these C# LINQ Queries to find a Minimum or Maximum with Where criteria fail?
I am working on a project where I want to run queries on a column in a database to find (a) the largest value less than or equal to a user-input minimum value, and the smallest value greater than or equal to a user-input maximum value. Also, I needed to handle the potential case where there might not be a result returned from one or both of these, so I specified a default value to be returned instead. However, when I ran this code, I got two cryptic errors in the Visual Studio output window:
Exception thrown: 'System.InvalidOperationException' in Microsoft.EntityFrameworkCore.Relational.dll
Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll
Apparently, they indicate that something in the 2 queries shown below caused a problem. But despite these errors, the application itself did not crash — it just stopped executing silently. I eventually found another way to do what I needed to do, but I’m left with the question — What’s wrong with these 2 statements?
fromValue = dbContext.SourceTable.Where(x => x.SourceColumn <= targetFromValue)
.Select(x => x.SourceColumn).DefaultIfEmpty(0).Max();
toValue = dbContext.SourceTable.Where(x => x.SourceColumn >= targetToValue)
.Select(x => x.SourceColumn).DefaultIfEmpty(99999).Min();
2
Answers
You are talking about a database, which implies you are using LINQ-To-Entities, not LINQ-To-Objects.
DefaultIfEmpty
may not be translatable to SQL.What you can do is:
this might be even better for you, as then the "no value found" case is null, which is easier to handle 🙂
To make it easier to understand what I’m talking about, let’s assume you have a table of Products:
And you want the largest price that is not larger than €10.00 (= smaller or equal)
In words: from each Product in the table of Products, select its Price. From the resulting sequence of Prices keep only those Prices that are smaller or equal than the limitValue. From the remaining sequence of Prices keep the largest one.
There is a problem: if there are no product prices that are smaller than the limitPrice, then Max does not work. If you think this might be a problem, then use MaxBy instead of Max. This will return null if the collection is empty.
If you are thinking of using this in more places, consider to create an extension method for this. If you are not familiar with extension methods, read Extension Methods Demystified
Usage:
Or if you want the largest Product.Id not larger than the limitValue:
You can intertwine this with other Linq methods:
Once you’ve got this one, the "smallest value not smaller than limitValue" is easy