Linq null expression

Looks like a stupid question, but I just don't get it. My essence:

public class Page { public int Id { get; set; } //... public int? ParentId { get; set; } } 

In the controller:

 db.Pages.First(x => x.ParentId == null); 

Works as expected (returns some element). But:

 int? test = null; db.Pages.First(x => x.ParentId == test); 

Throws Sequence contains no elements

What am I missing?

+6
source share
3 answers

I believe there is some uncertainty around zeros with some LINQ providers. Try:

 var query = db.Pages.First(x => (test != null && x.ParentId == test) || (test == null && x.ParentId == null)); 

Alternatively, use different queries for different situations:

 var query = test == null ? db.Pages.First(x => x.ParentId == null) : db.Pages.First(x => x.ParentId == test); 

This is mainly because SQL treats NULL as not equal to itself, therefore:

 WHERE X = Y 

will still fail if both X and Y are null values. Using the == null part (with a literal zero) results in conversion to ISNULL or regardless of the SQL equivalent.

I agree that this is a pain, and someone else may have a better workaround, but it can help you get away.

+10
source

You can do something like this as a workaround:

 int? test = null; if(test.HasValue) { db.Pages.First(x => x.ParentId == test.Value); } else { db.Pages.First(x => x.ParentId == null); } 

I assume int? in fact, the Nullable<int> our linq-to-entities provider does not compare everything correctly.

+2
source

Try this (modified according to gdoron's comment. Now this is exactly what Gideon wrote, so please accept it instead of mine):

 int? test = null; if(test.HasValue) { db.Pages.First(x => x.ParentId == test.Value); } else { db.Pages.First(x => x.ParentId == null); } 
+1
source

Source: https://habr.com/ru/post/908412/


All Articles