null result set throws an exception RRS feed

  • Question

  • When I perform the following query
    AdventureWorksDA.AW2008DataContext dc = new AdventureWorksDA.AW2008DataContext();
                var q = from per in dc.Persons
                        where per.BusinessEntityID == Id
                        select new { per.BusinessEntityAddresses.Address, per.BusinessEntityAddresses.AddressTypeID };
                foreach (var add in q)
                    this.Add(new Address(add.Address, add.AddressTypeID));
    (in this case using the ID 295 from the adventureworks database) q returns nothing - there is no address for this particular business entity. And yet, the foreach block runs but since add is null it throws an exception. I obviously can't check this beforehand since q doesn't populate until this line. This seems like an invalid condition - .NET should just skip the foreach block if nothing is returned. And oddly enough, running this query with some ID's causes exceptions but not with others (that return nothing also). So I'm completely confused as to what should be going on here.

    Any thoughts? Admittedly I'm just learning Linq but I don't know where to go from here.
    Monday, April 20, 2009 9:04 PM

All replies

  • The add variable should never be null in this case. The query is of type IQueryable<> and each member is of an anonymous type and cannot be null given your query.

    Could the Address class's constructor be throwing the exception instead? It's certainly possible that add.Address could be null.


    Query databases interactively in LINQ -
    Tuesday, April 21, 2009 4:08 AM
  • There are two possibilities here - one is that it doesn't find a person with that ID in which case no results will be returned the other is that BusinessEntityAddress is null because the person does not have an address.

    You could solve the second problem by adding && per.BusinessEntityAddress != null to the where condition.

    Tuesday, April 21, 2009 5:26 AM