InvalidOperationException Occurred in Linq orderby clause
Here is the linq statement I am using:
var sortedList =
(from p in OriginalList
where p.NValue != null
orderby Math.Abs(p.NValue.Value) descending
select p);
OriginalList is a list of Transaction objects with more than 10 thousand elements. NValue is nullable property of Transaction. Every time OriginalList is updated, the statement will be executed.
I have found that from time to time, this statement could throw the following exception: System.InvalidOperationException: Nullable object must have a value.
I tried to do unit testing and fed it with an OriginalList with only one Transaction. This Transaction has null NValue. It won't trigger this exception.
Anyone has idea what is going on here? Thanks a lot.
We are using Linq to SQL. Here is the stack trace:
2011-10-05 16:14:06,826 [SRV101 DC\Admin] [59] ERROR Utils.AProxy`1 - AProxy [TProxy] error during load
System.InvalidOperationException: Nullable object must have a value.
at CServer.TLoader.b__2(Trasaction p) in c:\...\TLoader.cs:line 61
at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
at S开发者_如何学Goystem.Linq.OrderedEnumerable`1.d__0.MoveNext()
at CServer.TLoader.GetMultipliers(IEnumerable`1 OriginalList) in c:\...\TLoader.cs:line 64
at CServer.TProxy.OnLoad() in c:\...\TProxy.cs:line 29
at Utils.AProxy`1.Load() in c:\...\AProxy.cs:line 252
The error you are seeing seems to indicate that you are trying to evalute .Value on a Null. Try using .GetValueOrDefault instead, otherwise change your where clause to check for HasValue rater than just comparing against null:
var sortedList h=
(from p in OriginalList
where p.NValue.HasValue
orderby Math.Abs(p.NValue.Value) descending
select p);
In your case p.NValue = Nullable thus p.NValue == null evalues to True, but p.NValue.HasValue == false.
I don't think Math.Abs is supported in Linq-to-Sql, so you can do something like this
var sortedList =
(from p in OriginalList
where p.NValue != null
orderby p.NValue.Value < 0 ? (p.NValue.Value * -1) : p.NValue.Value descending
select p);
精彩评论