WPF - Linq移动到构造函数导致null引用异常,怎么来的?

时间:2009-11-02 16:22:53

标签: c# wpf linq constructor

从我的Page_Loaded方法向构造函数移动代码(请参阅HERE),我现在遇到了我的Linq到实体查询的错误。它现在导致nullreferenceexception,我现在无法弄清楚为什么。请参阅下面的例外位置。

public Building()
{
    InitializeComponent();

    lvBuildings.ItemsSource = App.ocBuildings;
    getBuildings();
}


private void Page_Loaded(object sender, RoutedEventArgs e)
{

}

private void getBuildings()
{
    App.ocBuildings.Clear();
    var tehBuildings = from building in App.ents.Buildings
                       where building.Organisations.OrganisationID == App.selectedOrganisation.OrganisationID
                       select building;

    foreach (Buildings addBuilding in tehBuildings (<--Exception))
    {
        App.ocBuildings.Add(addBuilding);
    }

}

有人有什么想法吗?

谢谢, 钢钣。

2 个答案:

答案 0 :(得分:3)

看起来以下项目之一正在评估为null

  • App.ents
  • App.ents.Buildings
  • building.Organisations
  • App.SelectedOrganisation

这会导致在每个循环中抛出NullReferenceException,因为在使用查询之前不会对查询进行实际评估。

我们需要您提供更多信息,以确定哪一个为空。

答案 1 :(得分:0)

@JaredPar。

感谢您,我从未想过要查看我的客户端中的上一页(我正在加载)以获得答案。

我有一个代码按钮:

        Page newPage;
        if (App.ModeType == "Mode1"){ newPage = new MyClient.Pages.Mode1.Building(); }
        else if (App.ModeType == "Mode2") { newPage = new MyClient.Pages.Mode2.RiskQuestions(); }
        else { throw new NotImplementedException(); } ///Must be Mode3

            Organisations thisOrg = (Organisations)lvOrganisations.SelectedItem;
        App.selectedOrganisation = thisOrg;

        NavigationService.Navigate(newPage);

通过将App.selectedOrganisation移动到我设置“newPage”之前,一切都已修复。我想构造函数在我设置“newPage”时被调用。

为了清楚起见,对我有用的最终代码如下所示:

            Organisations thisOrg = (Organisations)lvOrganisations.SelectedItem;
        App.selectedOrganisation = thisOrg;

        Page newPage;
        if (App.ModeType == "Mode1"){ newPage = new MyClient.Pages.Mode1.Building(); }
        else if (App.ModeType == "Mode2") { newPage = new MyClient.Pages.Mode2.RiskQuestions(); }
        else { throw new NotImplementedException(); } ///Must be Mode3

        NavigationService.Navigate(newPage);