【问题标题】:Updating database using entity framework throws Null Reference Exception使用实体框架更新数据库会引发空引用异常
【发布时间】:2012-12-10 11:28:31
【问题描述】:

我正在使用实体框架为组织创建一个桌面应用程序,以便将他们的数据输入数据库以显示他们的记录。

我使用data template 创建了一个tab control,该data template 已经过验证,使他们能够保存必要的必填字段,到目前为止一切都很好。

我在页面上使用了一系列不同的数据网格来显示已添加的详细信息。在此页面内,它包含一系列不同的commands,以允许用户添加、更新或删除内容(取决于表格,只允许他们更新)。

但这就是我不解的地方。到目前为止,添加和删除方法工作得很好,但是当涉及到更新表时,它会抛出一个Null Reference Exception

这里有一些代码 sn-ps; 视图模型:

    public List<Employee> LoadEmployee
    {
        get
        {
            using (DBEntities context = new DBEntities())
            {
                var query = from e in context.Employees
                            select e;
                return query.ToList<Employee>();
            }
        }
    }

    public void UpdateEmployee()
    {
        var employee = new Employee();

        using (DBEntities context = new DBEntities())
        {
            //var emp = context.Employees.Where(e => e.EmployeeID == employee.EmployeeID).FirstOrDefault();

            var emp = (from a in context.Employees
                       where a.EmployeeID == EmployeeID
                       select a).FirstOrDefault();

            if (emp == null)
            {
                emp.EmployeeID = EmployeeID;
                emp.OrganisationID = OrganisationID;
                emp.Title = Title;
                emp.FirstName = FirstName;
                emp.Surname = Surname;
                emp.Position = Position;
                emp.DateOfBirth = DateOfBirth;
                emp.Address = Address;
                emp.Country = Country;
                emp.Postcode = Postcode;
                emp.PhoneNumber = PhoneNumber;
                emp.MobileNumber = MobileNumber;
                emp.FaxNumber = FaxNumber;
                emp.Email = Email;
                emp.NINumber = NINumber;
                emp.ChargableResource = ChargableResource;
                emp.ChargeOutRate = ChargeOutRate;
                emp.TimeSheetRequired = TimeSheetRequired;
                emp.WorkShift = WorkShift;
                emp.WorkShift = BenefitsProvided;

                //context.Employees.Attach(emp);
                context.SaveChanges();

                MessageBox.Show("Updated Employee Details");
            }
            else
            {
                MessageBox.Show("Unable to update selected item.");
            }
        }
    }

    public Employee _SelectedEmployee;
    public Employee SelectedEmployee
    {
        get
        {
            return _SelectedEmployee;
        }
        set
        {
            if (_SelectedEmployee == value)
                return;

            _SelectedEmployee = value;
            OnPropertyChanged("_SelectedEmployee");
        }
    }

代码背后:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listview.DataContext = new EmployeeViewModel();
    }

    private void btnupdate_Click(object sender, RoutedEventArgs e)
    {
        var emp = new EmployeeViewModel();

        Employee selected = listview.SelectedItem as Employee;

        if (selected == null)
            MessageBox.Show("You must select a 'Employee' before updating.");
        else
        {
        UpdateEmployeeView update = new UpdateEmployeeView();

        update.ShowDialog();
        Window_Loaded(null, null);
        }
    }

xaml;

            IsSynchronizedWithCurrentItem="False"
            ItemsSource="{Binding LoadEmployee}"
            SelectedItem="{Binding SelectEmployee}" Grid.RowSpan="2">

首先,当用户从数据网格中选择一行时,我希望更新该特定行。我已将我的视图模型中的属性绑定到我的 xaml 中的文本字段,以便它传递到视图模型。我还尝试在我的视图模型中对 ID 属性进行硬编码; public int _EmployeeID = 11; public int _OrganisationID = 4; 但这仍然会抛出 Null Reference Exception

谁能帮我解决这个问题?我一直在尝试各种不同的方法,但仍然没有用。我是 WPF 的新手并尝试实现 MVVM,显然它不是完全的 MVVM,但我正在缓慢但肯定地学习实现它的正确方法。 干杯。

【问题讨论】:

    标签: c# wpf entity-framework data-binding


    【解决方案1】:
    if (emp == null)
     {
    

    添加行:

    emp = new Employee();
    

    否则,您将值分配给 null 变量。

    【讨论】:

    • 抱歉不同意你的观点,Michael,但这只是意味着如果没有指定 id 的员工,你正在添加一个新员工,这应该只是抛出一个异常,因为它是一个更新方法,而不是 SaveOrUpdate 方法。 Gregory,如果可能的话,你还应该稍微清理一下你的代码,因为你使用了很多变量却什么也不做,以及创建的对象给你已经拥有的东西赋予了新的意义(var emp = new EmployeeViewModel(); 而不是正确使用 DataContext 并将其转换为正确的对象类型)。
    • 感谢您的回复。我已经尝试过了,但它似乎仍然返回 MessageBox.show("unable to selected item");
    • 感谢您的回复@Raposo,显然这不是最后一段代码。我一直在尝试做不同的事情来让它工作,而且我是 wpf 和 C# 的新手,所以我边走边学。
    • 顺便说一句,Gregory,你看过 MVVM Light (mvvmlight.codeplex.com) 吗?它可以帮助您实现 MVVM 模式,您可以将其作为 NuGet 包添加到您的应用程序中。
    • @Raposo 是的,我已经看过 MVVM light,但目前,我只是想专注于尝试实现此功能作为其主要关注点之一。我只是想更好地了解 WPf 的工作原理,然后再尝试一次让我的大脑爆炸太多知识。
    【解决方案2】:

    在我的代码隐藏中,我已将 TextBox 映射到 EF 中的 Entities(我知道这是实现 MVVM 的不正确方法,但我仍在学习这将改变。

    基本上,我将所有 textbox 分配给项目,而不是分配 ID。因此它不允许我更新,因为由于没有分配 ID,它无法识别表中要更新的项目。

    像这样;

    txtID.Text = type.OrganisationTypeDetailID.ToString();
    

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多