We have recently deployed our new website. We recommend using the new website as some features have been deprecated. The old website is still available till Sep. 30, 2018 and can be accessed here.

LINQ SUM - An exception of type 'System.OverflowException' occurred in System.Data.dll but was not handled in user code - Conversion overflows

Tuesday, August 7, 2018 / mcchu28


Possibly save 1 hour of your time: When you use LINQ to sum up values from many records, the value may be so big that it cause this overflow exception.

When I check the max decimal number in .NET, it says the biggest value is 79,228,162,514,264,337,593,543,950,335. I found out from sql profiler the value returned is 214,805,108,008,621.897184851000000. This is smaller than the max decimal however I think the issue has to do with the number of significant digits.

Solution 1: You can return the list of records first and then call the SUM method. In .NET this doesn't seem to be an issue.

decimal total = query.ToList().Sum(x => x.Value ?? 0);

Solution 2: This is a hack. You can divide the value by 10000 or more to make the value smaller when it sum. And then once you have the result, you multiply it by 10000 again.

This fix may cause a small performance issue because it has to do the extra division before summing up.

decimal total = query.Sum(x => x.Value / 10000) * 10000; 

Solution 3: I didn't try this but I found other solution building their own LINQ SUM extension that use the checked function that will not check for overflow.