recursive function for hierarchically data
my model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace amief.Models
{
public class WebsiteModels
{
public static void getPagesForPage(int pageId, dbDataContext db, List<page> myPages)
{
var pages = (from p in db.pages
where p.pageParent == pageId
select p);
foreach (var item in pages)
{
myPages.Add(item);
getPag开发者_运维百科esForPage(item.pageId, db, myPages);
}
}
}
}
calling the procudure
List<page> myPages = null;
WebsiteModels.getPagesForPage(0, db,myPages);
i'm getting an error
System.NullReferenceException was unhandled by user code Message=Object reference not set to an instance of an object.
on line "myPages.Add(item);"
I don't understand the error...
You're setting myPages
to null
before passing it to WebsiteModels.getPagesForPage()
. Therefore, the calls to myPages.Add(item);
in your loop raise a NullReferenceException
because you can't call a method on a null
object.
You probably want:
List<page> myPages = new List<page>();
WebsiteModels.getPagesForPage(0, db, myPages);
Well, "myPages" IS null, so calling a method on it results i a NullReferenceException. You should rather write
myPages = new List<page>();
精彩评论