【问题标题】:NullReferenceException from linq query in database project来自数据库项目中 linq 查询的 NullReferenceException
【发布时间】:2014-05-15 02:27:52
【问题描述】:

我正用头撞墙,试图弄清楚为什么当我单击按钮时,NullReferenceException 说我的 dbcontext 在 linq 查询中为空!!!我不明白,因为当表单加载医院实体时,我的 dbcontext 会被填满(见下文):

 using System;
 using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DisplayPatientsTable
{
public partial class PatientForm : Form
{


    public PatientForm()
    {
        InitializeComponent();
    }

    //Entity Framework dbcontext. All data passes through this object and the database
    private HospitalDatabase.HospitalEntities dbcontext = null;

    private void PatientForm_Load(object sender, EventArgs e)
    {
        RefreshPatients();
    }

    private void RefreshPatients()
    {
        //Dispose of old dbcontext, if any
        if (dbcontext != null)
        {
            dbcontext.Dispose();

            //create new dbcontext so we can reorder records based on edits

            dbcontext = new HospitalDatabase.HospitalEntities();

           //use LINQ to order the Addresses table contents by last name, then first name

            dbcontext.Patients.OrderBy(Patients => Patients.Pat_Last_Name)
            .ThenBy(Patients => Patients.Pat_First_Name)
            .Load();


            // specify DataSource for PatientsBindingSource
            patientBindingSource.DataSource = dbcontext.Patients.Local;
            patientBindingSource.MoveFirst(); // go to the first result
            textBox1.Clear(); //clear the Find TextBox

        }
    }

    private void pat_First_NameLabel_Click(object sender, EventArgs e)
    {

    }


    private void button1_Click(object sender, EventArgs e)
    {
        // use LINQ to create a data source that contains only people
        // with last names that start with the specified text

        // use LINQ to filter contacts with last names that
        // start with findTextBox contents
        //Entity Framework dbcontext. All data passes through this object and the database

        if (dbcontext != null)
        {
            dbcontext.Dispose();

            //create new dbcontext so we can reorder records based on edits

            dbcontext = new HospitalDatabase.HospitalEntities();
        }

        var query = from patient in dbcontext.Patients
                     where patient.Pat_Last_Name.StartsWith(textBox1.Text)
                     orderby patient.Pat_Last_Name, patient.Pat_First_Name
                     select patient;






        //display matching contacts
      //  patientBindingSource.DataSource = query.ToList();
       // patientBindingSource.MoveFirst(); //

        // don't allow add/delete when contacts are filtered
        bindingNavigatorAddNewItem.Enabled = false;
        bindingNavigatorDeleteItem.Enabled = false;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        // allow add/delete when contacts are not filtered
        bindingNavigatorAddNewItem.Enabled = true;
        bindingNavigatorDeleteItem.Enabled = true;
        RefreshPatients(); //change back to initial unfiltered data
    }

    private void patientBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        Validate(); // validate input fields
        patientBindingSource.EndEdit();

        //try to save changes
        if (dbcontext == null)
        {
            MessageBox.Show("FirstName and LastName must contain values");
        }
            dbcontext.SaveChanges();


        RefreshPatients();
    }


    }
 }

【问题讨论】:

  • var query = from patient in dbcontext.Patients where patient.Pat_Last_Name.StartsWith(textBox1.Text) orderby patient.Pat_Last_Name, patient.Pat_First_Name select patient;
  • 上面的评论是这个异常发生的地方。当我尝试保存时也会发生这种情况。由于某种原因,DbContext 仍然为空!

标签: c# database linq ado.net-entity-data-model


【解决方案1】:

如果dbcontext != null...,您只会运行以下行,但当您的表单首次加载时它是null,因此if 块内的代码永远不会执行。

dbcontext = new HospitalDatabase.HospitalEntities();

你必须重新设计你的逻辑。也许像这样简单,在处理对象之前检查值,然后运行其余代码。

//Dispose of old dbcontext, if any
if (dbcontext != null)
    dbcontext.Dispose();

//create new dbcontext so we can reorder records based on edits
dbcontext = new HospitalDatabase.HospitalEntities();

请注意,我无法评论像这样处理和创建新实体是否是一种好习惯 - 我对这项技术还不够熟悉。我相信确实如此。

【讨论】:

  • 做到了!我什至没有注意到我是用 if 语句做的(把括号放在错误的地方!)但是我有另一个例外....
  • 当我遇到以下情况时,我收到了一个 EntityCommandException:
  • dbcontext.Patients.OrderBy(Patients => Patients.Pat_Last_Name).ThenBy(Patients =>Patients.Pat_First_Name).Load();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多