Frage

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?

War es hilfreich?

Lösung

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();

Andere Tipps

The issue is the .ToArray() on you first query. This linq query is creating a native query to your CrmContext provider:

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

The .ToArray() is causing the linq query to be run immediatly and returns a plain old array of objects. The array is not attached to your CrmContext object.

However, this query is using Linq to Objects to iterate over the array returned in the first call. It is not generateing a native query to your CrmContext provider.

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

Its effectively the same as using a foreach loop to iterate over each element in the array so you have to worry about checking for possible null values that were returned by your first query.

I don't understand your question. You're saying that the homepage is a web page and it is NOT hidden from the sitemap, so why wouldn't you expect the homepage to show up in your query as a p?

Anyway, you can simply skip anything with p == null:

Adx_webpage[] childPages = (FROM p in WebPages
                            WHERE p.adx_parentpageid != null &&
                                  p.adx_parentpageid.Id == page.Id
                            SELECT p).ToArray();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top