Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Linq Behavior - ToList()

I have two similar queries theoretically returning the same results:

var requestNotWorking = SessionManagement.Db.Linq<Item>(false).Where(i => 
                        i.Group != null && i.Group.Id == methodParameter)
                       .ToList();

This request returns 0 items, even though it is supposed to return one. The following is a rewrite of the latter but with a call to the ToList() method. This request works and returns the item expected in the first query!

var requestWorking = SessionManagement.Db.Linq<Item>(false).ToList().Where(i => 
                     i.Group != null && i.Group.Id == methodParameter).ToList();

Note: SessionManagement.Db.Linq<Item>(false)is a generic Linq to Nhibernate method with the boolean attribute determining if the request must be executed in the cache (true) or the database (false). There is supposedly nothing wrong in this method as it works normally in many other parts of the solution. The mapping of Item is nothing fancy: no bags and the following parameters: lazy="false" schema="dbo" mutable="false" polymorphism="explicit"

Why is this so?

Edit:

The generated sql request of requestNoWorking ends with :

(Item.Group_ID is not null) and Item.Group_ID=@p0',N'@p0 int',@p0=11768

The generated sql request of requestWorking is roughly a select * from dbo.Items

like image 502
Keysharpener Avatar asked Jan 03 '13 15:01

Keysharpener


2 Answers

i'm assuming the nhibernate session thing you've got going on there returns a queryable. if so, the evaluation of the first query is delayed until the .ToList() call, and the entire query is run on the server. I would suggest that you run a trace on the sql server if possible, or perhaps download NHProf to see what the actual query being executed is.

the second query is evaluated as soon as you hit the first .ToList(), so you're pulling the whole table back from the db, and then filtering using .net. i honestly can't tell you why they would be evaluating differently, but i assume there is something with the mapping/configuration that is causing the db query to be written slightly wrong.

like image 112
nathan gonzalez Avatar answered Sep 19 '22 15:09

nathan gonzalez


I was very interested by your theory on c.Group.Id != null, which I found logical even though it contradicted other pieces of code in my solution. However, removing it did not change anything. I found that removing mutable="false"property solved the problem. It seems a bit magical but it worked.

The requests I posted were in fact happening in methods checking the possibility of update/deletion. My conclusion is that somehow making Item immutable falted the results. But what I don't understand is why requestWorking worked then!

like image 34
Keysharpener Avatar answered Sep 20 '22 15:09

Keysharpener