使用实体框架

时间:2015-06-13 13:14:53

标签: c# entity-framework

我正在尝试从数据库中的表中删除一行,但我不断收到null reference exception

我知道我写的代码不是从ComboBox获取ID号,但我不知道如何解决它。

这是我的代码:

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    try
    {
        //select row to delete
        Doctor del = ((Doctor)cbDocIdd.SelectedItem);
        Doctor deleted = (from d in MainWindow.nlh.Doctors
                          where d.DoctorID == del.DoctorID
                          select d).First();
        //delete row from db
        MainWindow.nlh.Doctors.DeleteObject(deleted);
        //Save to database
        MainWindow.nlh.SaveChanges();
        MessageBox.Show("Doctor deleted");
        this.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

非常感谢任何帮助。

这是用于填充组合框的代码:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        cbDocIdd.DataContext = MainWindow.nlh.Doctors;
    }

2 个答案:

答案 0 :(得分:2)

您需要使用.FirstOrDefault检查是否找到了有效的实体:

//select row to delete
Doctor del = ((Doctor)cbDocIdd.SelectedItem);
Doctor deleted = (from d in MainWindow.nlh.Doctors
                  where d.DoctorID == del.DoctorID
                  select d).FirstOrDefault();

// check if it even exists!!
if(deleted != null) 
{ 
    //delete row from db
    MainWindow.nlh.Doctors.DeleteObject(deleted);
    //Save to database
    MainWindow.nlh.SaveChanges();
    MessageBox.Show("Doctor deleted");
    this.Close();
}

如果您使用.First()并且具有该ID的医生不存在,您将获得例外

另外:在以下语句中使用它之前,请确保del值为OK且 not null 。同样适用于MainWindow - 你确定这不是null吗?

更新:你能试试这两行并告诉我结果是什么吗?

//select row to delete
object selectedObj = cbDocIdd.SelectedItem;

if(selectedObj != null)
{
    string typeOfSelectedObj = selectedObj.GetType().Name;
}

Doctor del = ((Doctor)cbDocIdd.SelectedItem);

selectedObj是否为空?如果是这样的话:类型是什么?

更新#2:确定 - 所以医生确实存在并且正在返回确定 - 你能为我试试吗?

替换此行:

Doctor del = ((Doctor)cbDocIdd.SelectedItem);

代之以:

Doctor del = cbDocIdd.SelectedItem as Doctor;

当你运行时 - del现在是null以外的其他内容吗?

解决方案:

最后,真正的这个代码破坏的原因在于对MainWindow.nlh.Doctors.DeleteObject(deleted);的调用导致事件处理程序触发,其中包括以下代码:

private void cbDocIdd_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // populate with DoctorID from db
    Doctor deletedDoc = ((Doctor)cbDocIdd.SelectedItem);
    tbLastName.Text = deletedDoc.LastName.ToString();
    tbFirstName.Text = deletedDoc.FirstName.ToString();
    tbLicenseNumber.Text = deletedDoc.LicenseNumber.ToString();
}

但在这种情况下,当医生被删除时,deletedDoc被返回为NULL,但没有检查以确保只访问非NULL object .....因此,一个臭名昭着的" null-reference异常"在尝试访问deletedDoc.LastName属性时被抛出......

答案 1 :(得分:0)

当您尝试使用包含空值的方法时,会显示

“null reference exception”。

例如,如果产品具有空值或者像product = null一样分配给null,那么您不能将方法用作product.count()或其他东西,因为不支持null.count()

    Doctor deleted = (from d in MainWindow.nlh.Doctors
                      where d.DoctorID == del.DoctorID
                      select d).FirstOrDefault(); 

use this and check null.