Oscar
Oscar

Reputation: 1147

How can I fix this LINQ function?

I'm using this code:

            var nextLevel = (from p in cd.Objective
                             where p.Parent_ObjectiveID == null
                             select p.Level);

And it works, by the moment it returns no elements (because I don't have any element in my database). Although I'd like to know the Top level doing this:

            var nextLevel = (from p in cd.Objective
                             where p.Parent_ObjectiveID == null
                             select p.Level).Max();

But I get an error:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

Parent_ObjectiveID is a nullable int and level in only int.

Upvotes: 2

Views: 108

Answers (1)

Jacob Proffitt
Jacob Proffitt

Reputation: 12768

Max is looking to return an int because that's the type of p.Level, but forced to return a null (because there are no items in the query). If you cast p.Level to a nullable int, your query should work.

var nextLevel = (from p in cd.Objective
                 where p.Parent_ObjectiveID == null
                 select (int?)p.Level).Max();

Upvotes: 4

Related Questions