None of these objects are null, i did check that.
Humor me and check again. Run the following code instead of your query:
products.ToString();
products.Select(x => x.ToString()).ToArray();
products.Select(x => x.SubCategories.ToString()).ToArray();
subCategories.ToString();
products.Select(x => x.SubCategories.Select(sc =>
sc.ToString()).ToArray()).ToArray();
If *none* of these statements generate a NullReferenceException, *then* the
problem is interesting. As in, "show me the stack trace" interesting.
I didnt include code as i was hoping for a generic response,
Well, I'd say you got what you asked for. I hope you also see the inherent
drawback in doing this: we now have to do rounds of questions and answers
before we can get near the actual problem.
I have read in other places that this was not possible in LINQ
That *what* wasn't possible in LINQ? Executing LINQ queries? Because that's
what you're doing.
A NullReferenceException indicates a bug, not an unsupported feature. Your
query should return a result. Whether it's the result you want is another
matter.
public class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<SubCategory> SubCategories { get; set; }
}
public class SubCategory
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Product> Products { get; set; }
}
Are these your actual classes or idealized versions? In particular, does
SubCategory happen to override Equals or implement IEquatable?
IList<SubCategories> subCategories = new Services.SubCategoryService
().Fetch(); //Retrieves all Sub Catagories.
IQueryable<Product> products = _repository.Query(); // this returns a
IQueryable object via NHibernate.
products.Where(x => x.SubCategories.Any(sc => subCategories.Contains
(sc)));
More possible causes for error can be added to the list: there could be a
bug in NHibernate or the way you use it.
subCategories is not null, Products is not null, and neither is
SubCategories in products.
That's not a full set of checks.
Yet i get a null exception.
I do find linq quite difficult to debug.
LINQ basically generates complex expressions. You debug those like any
other: break them up in explicit steps and check intermediate results. But
yes, lots of calls may be involved that you don't see coming, especially if
you're operating on highly abstracted sequences.
NullReferenceExceptions deserve special mention because they're
intrinsically hard to debug, LINQ or no. By the time you get the exception
it's too late: you only know that a reference is ultimately null, not *why*
it's null. This is why it's critical that every piece of code in the chain
check for nulls as soon as possible (or reasonable) and throw an
ArgumentNullException instead, so you can identify exactly where assumptions
were violated. Obviously, this is not happening somewhere, possibly in a
piece of code that omits this for performance reasons.