0

I have converted a windows forms application from .net 3.5 to .net 4. I am using Linq to operatate with data. Now I have some problems with Linq, because in the new version it throws an exception when trying to make a query over null resultset. For example (resultSet is of type System.Linq.IQueryable<>):

var orderedResult = from d in resultSet
                     orderby d.ID descending
                     select d;

Throws an exception "Value can not be null" when resultSet is null. It was working fine in .NET 3.5. How can I avoid this errors in .NET 4, making the least change in code? Are there any setting I can switch, so that when the resultSet value is null, not any query is done, without throwing an exception?

The problem is that I have thousands of statements like the one above. If I have to check for every of them with "if resultsSet != null", it will be a difficult solution. In .NET version 3.5 query over null resultset was just returning null. Can I make it the same for .NET 4?

  • yes, there is an **if statement** to check value is `null` or `not`.It is very common in all programing languages. – Selman Genç Jan 24 '14 at 04:54
  • 1
    _" In .NET version 3.5 query over null resultset was just returning null"_ - that is not true. `from d in (IQueryable)null select d` on .NET 3.5 also throws an `ArgumentNullException` saying "Value can not be null". You didn't just change the framework version from 3.5 to 4, right? – CodeCaster Jan 24 '14 at 11:31

3 Answers3

2

I'm pretty sure that if the resultset was null in .NET 3.5 it would throw an exception as well. LINQ is syntactic sugar on a set of extension-methods. When the object is null, the extension-methods aren't available. You should evaluate the changes in your DAL. If, for example, you are using LINQ to SQL, there might be some changes that apply to you: http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40.

denniebee
  • 501
  • 4
  • 6
0
if(resultSet != null)
{
    //perform your action here
}
Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29
  • 1
    The problem is that I have thousands of statements like the one in my first post. If I have to check for every of them if resultsSet != null, it will be difficult solution. In .NET version 3.5 query over null resultset was just returning null. Can I make it the same for .NET 4? – user3230553 Jan 24 '14 at 11:18
0

Let's call a method on null!

public static IEnumerable<TEntity> EmptySetIfNull( this IEnumerable<TEntity> enumerable )
{
    if( null == enumerable )
    {
        return new TEntity[] { };
    }

    return enumerable;
} 

usage:

IEnumerable<ClassA> resultSet = null;

var orderedResult = from d in resultSet.EmptySetIfNull()
                     orderby d.ID descending
                     select d;
Moho
  • 15,457
  • 1
  • 30
  • 31