6

Looks like stupid question, but I just dont get it. My entity:

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

In 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 do I miss?

1
  • 1
    Are you using linq-to-entities? This has nothing specific to do with asp.net-mvc? Commented Feb 14, 2012 at 9:56

3 Answers 3

10

I believe there's an oddity around nulls 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 the different situations:

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

Basically this is because SQL treats NULL as unequal to itself, so:

WHERE X = Y

will still fail if both X and Y are null values. Using the == null part (with a literal null) forces a conversion to ISNULL or whatever the SQL equivalent is.

I agree it's a pain, and someone else may have a better workaround, but this may help you get going.

Sign up to request clarification or add additional context in comments.

Comments

2

You could 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'm assuming since int? is actually a Nullable<int> our linq-to-entities provider isn't comparing things right.

Comments

1

Try this (modified according to gdoron's comment. It now is exactly what gideon posted, so please accept his 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);
}

2 Comments

Won't work. Value - The value of the current Nullable(Of T) object if the HasValue property is true. ==> An exception is thrown if the HasValue property is false. <==
thx for this solution, but i just wanted to understand that oddity of LINQ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.