I have this code to find the root node of a tree:
Guid? currentNode = null;
var root = db.RecursiveTrees.Where(x => x.ParentId == currentNode).ToList();
This query returns 0 results.
If I run this query I get the expected row returned:
var root = db.RecursiveTrees.Where(x => x.ParentId == null).ToList();
Why doesn't the first query work (using the latest version of entity framework)?
EDIT:
Workaround:
List<RecursiveTree> root;
if (nodeid == null)
root = db.RecursiveTrees.Where(x => x.ParentId == null).ToList();
else
root = db.RecursiveTrees.Where(x => x.ParentId == new Guid(nodeid)).ToList();
It will return an empty enumerable. It won't be null.
LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.
NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false". Save this answer.
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
This is a known bug in LINQ to Entities when dealing with nullable value-types. According to the relevant Connect issue, this will be fixed in the next release.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With