Search code examples
c#linqdynamics-crm-2011sitemapprovider

WHERE clause in LINQ query seems to be failing


Please forgive any naivety, I'm brand new to the world of C#. Let me know if I've left out helpful information.

I'm building a custom SiteMapProvider for the Customer Portal for Dynamics CRM 2011. First I initialize an array:

public Adx_webpage[] WebPages;

which gets populated thusly:

public MyProvider()
{
    WebPages = (FROM p in CrmContext.Adx_webpageSet WHERE p.Adx_HiddenFromSitemap != true SELECT p).ToArray();
}

Later, I try to query WebPages[] like so:

Adx_webpage[] childPages = (FROM p in WebPages WHERE p.adx_parentpageid.Id == page.Id SELECT p).ToArray();

When I run this through the debugger, I get a NullReferenceException which points at the condition in my WHERE clause saying that p.adx_parentpageid.Id is null, which is true for the home page of the site. Which leads to the question:

Why would this query turn up the home page as a p in my query? What am I misunderstanding?


Solution

  • Your first line

        WebPages = (FROM p in CrmContext.Adx_webpageSet WHERE p.Adx_HiddenFromSitemap != true SELECT p).ToArray();
    

    Will return you all pages that are not hidden in your site map. But this is also including your home page which has no parent id. So when your second query enumerates over this collection it is going to attempt to access this property which is null and throw a null reference exception. You just need to cater for this in your query.

    Adx_webpage[] childPages = 
    (FROM p in WebPages WHERE 
    p.adx_parentpageid.Id != null &&
    p.adx_parentpageid.Id == page.Id SELECT p).ToArray();