سؤال

I am slamming my head against the wall trying to figure out why when I click the button, a NullReferenceException is saying that my dbcontext is null at the linq query!!! I don't understand, as I have the dbcontext get filled when the form loads with a hospital entity (see below):

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


    }
 }
هل كانت مفيدة؟

المحلول

You're only running the following line if dbcontext != null... but it's null when your form first loads, so the code inside that if block is never going to execute.

dbcontext = new HospitalDatabase.HospitalEntities();

You'll have to rework your logic. Maybe something as simple as this, where you check the value before disposing of the object, but then run the rest of the code regardless.

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

Note that I can't comment on whether disposing and creating a new entity like this is a good practice - I'm not familiar enough with the technology. I'll trust that it is.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top