[CSHARP-2191] LINQ is not working as intended Created: 14/Feb/18  Updated: 27/Oct/23  Resolved: 14/Feb/18

Status: Closed
Project: C# Driver
Component/s: Linq
Affects Version/s: 2.5
Fix Version/s: None

Type: Task Priority: Minor - P4
Reporter: Ed Lomonaco Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: Bug, question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 10, .NET 4.7.1


Backwards Compatibility: Fully Compatible

 Description   

The following code works:

var dataCollection = Db.GetCollection<User>("User");
var results = dataCollection.AsQueryable().Where(p => p.Id == userId);

but it doesn't work if you do it like this:

var dataCollection = Db.GetCollection<User>("User");
var query = dataCollection.AsQueryable();
 
query.Where(p => p.Firstname == "Tom");
query.Where(p => p.Lastname == "Smith");

it seems if its not part of the original variable, then mongo LINQ will totally ignore it



 Comments   
Comment by Robert Stam [ 14/Feb/18 ]

You're welcome!

Comment by Ed Lomonaco [ 14/Feb/18 ]

ak ok, thanks for that clarification

Comment by Robert Stam [ 14/Feb/18 ]

LINQ is a chained API and each call to Where (or any other LINQ operator) returns a new instance. So in your second example each call to Where is returning a new object but since you don't assign it to a variable it gets lost.

If you don't want a single chained expression but rather need to build up your query little by little you need to assign the intermediate queries to some variable (either the same one or another one).

For example:

var query = (IQueryable<User>)collection.AsQueryable();
query = query.Where(p => p.Firstname == "Tom");
query = query.Where(p => p.Lastname == "Smith");

Generated at Wed Feb 07 21:41:51 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.