Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't using a nullable Guid work in this linq query?

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();     
like image 691
woggles Avatar asked Dec 28 '11 08:12

woggles


People also ask

Can LINQ return null?

It will return an empty enumerable. It won't be null.

Is null in LINQ C#?

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.

Is null SQL in LINQ?

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.

Is LINQ inefficient?

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.


1 Answers

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.

like image 130
Ani Avatar answered Sep 20 '22 16:09

Ani