[CSHARP-2302] c# driver throws on aggregate function when the source sequence is empty Created: 19/Jun/18 Updated: 27/Oct/23 Resolved: 26/Nov/18 |
|
| Status: | Closed |
| Project: | C# Driver |
| Component/s: | Linq, Read Operations |
| Affects Version/s: | 2.6.1 |
| Fix Version/s: | None |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | Itzhak Kagan | Assignee: | Robert Stam |
| Resolution: | Works as Designed | Votes: | 2 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Environment: |
c# driver 2.6.1, |
||
| Description |
|
I have a class:
I have a function that gets the PatientSystemId as parameter GetDynamicFormsAsync(long patientSystemId) I run the following query:
When there are documents in the database that meet the filter criteria I do get the Max date as desired. However, if there is no document meeting the query criteria then I get a run-time exception:
When patientSystemId parameter equals 51, the following query is generated:
When running this query in mongo shell, no exception occurs. Can you please address this bug / issue. Thanks, |
| Comments |
| Comment by Robert Stam [ 27/Nov/18 ] | |||||||||||||||
|
The Max function in LINQ is defined (by Microsoft) to throw an InvalidOperationException when the sequence is empty. To prove this to yourself try the following code:
The same is true of other methods like Average:
It is correct that you should only use the Max function when you know the sequence is not empty. That is not a limitation of the MongoDB C# driver, it's just the way Max and Average are defined. | |||||||||||||||
| Comment by Ilya Sh [ 27/Nov/18 ] | |||||||||||||||
|
FOA Generally while a query works in the shell it is expected to work similarly in any driver, eventually.
| |||||||||||||||
| Comment by Itzhak Kagan [ 27/Nov/18 ] | |||||||||||||||
|
So actually what you are saying is to never use the linq Max function since there is always a chance to have no match. | |||||||||||||||
| Comment by Robert Stam [ 26/Nov/18 ] | |||||||||||||||
|
The LINQ Max method by definition is supposed to throw an InvalidOperationException if there are no values. So the following query MUST throw an InvalidOperationException if no documents match:
I can offer two alternative queries that will return a nullable DateTime if there are no matching documents. The first alternative is to sort by descending ModifiedDate and take the first one, if any (it will be the max):
This will perform well as long as the number of matching documents is small enough that sorting them is not time consuming. The second alternative is to use the aggregation pipeline directly instead of LINQ:
| |||||||||||||||
| Comment by Axente Adrian [ 21/Nov/18 ] | |||||||||||||||
|
Is there any possibility to implement DefaultIfEmpty extension method in the Mongo Linq provider? This will solve the problem.
Best Regards Axy |