I have the following two lines of code in my program. The goal is to return the highest number from the Value field.
MyDataContext context = new MyDataContext();
long? id = (long?)context.MyTable.Max(x => x.Value);
The Value field is a bigint field in the table. The table also cannot guarantee that it contains rows, in fact that it is scenario I am testing now. I am attempting to run this when MyTable has no rows.
The second line returns an invalid operation exception.
The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type.
I’ve tried it several different ways but I am unable to get this to work. I obviously not understanding something important about nullable types in C#.
EDIT (solution):
Thanks to Chris’s answer I was able to find the actual cause of my problem and solution. It turns out that it wasn’t so much that the Value field was null but that since x inside the lambda expression was a null row. So I added a check inside the lambda to see if x was null, if not then I can safely check if Value is null.
MyDataContext context = new MyDataContext();
long? id = context.MyTable.Max(x => x == null ? (long?)0 : (long?)x.Value);
Your max function is trying to return an Int64. The overload of Max you are using is defined here on MSDN. You’ll see that it takes a parameter
Func<TSource, long> selector. This is your lambda expression and says that you’ll give it a TSource and it will return a long (ie Int64). What your function is doing is when x.Value is null returning a null value which is of course not valid to as an Int64.In this case you should be able to use something like:
This means that if x has a value it returns that and otherwise returns the minimum possible value which will only ever be the max if everything is null.
I should disclaim that this code is untested but should give you the right idea.
edited: I originally was assuming that this was a nullable long but it turns out there are overloads that support that so I now assume that x is not a nullable long, just looks a bit like one if you squint int eh right way.