简体   繁体   中英

Updating database using entity framework throws Null Reference Exception

I'm using entity frameworks to create a desktop application for an organisation to enter their data into a database to show their records.

I've created a tab control using a data template which has been validated that enables them to save the required fields necessary which, so far so good.

I have used a series of different data-grids on a page to show the details which have been added. Within this page, it contains a series of different commands to allow the user to either add, update or delete content (depending on the table, only allows them to update).

But this is where I become unstuck. So far, the add and delete methods work perfectly, but when it comes down to updating the tables, it throws a Null Reference Exception .

Here are some code snippets; View-Model:

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

Code Behind:

    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">

Firstly, When a user selects a row from the data grid, I want that specific row to update. I've bound my properties in my view-model to the text fields in my xaml so that it passes through to the view model. I also tried to hard code the ID properties within my view model; public int _EmployeeID = 11; public int _OrganisationID = 4; but this still throws the Null Reference Exception .

Can anyone help to solve this issue with me? I've been trying various different ways and still no use. I'm new to WPF and trying to implement MVVM, obviously its not fully MVVM but I'm slowly but surely learning the correct way of implementing it. Cheers.

if (emp == null)
 {

Add line:

emp = new Employee();

Otherwise you are assigning values to null variable.

Within my code-behind I have mapped the TextBox to the Entities in EF (I know this is the incorrect way of achieving MVVM but as I am still learning this will be changed.

Basically, I was assigning all the textbox to the items and was not assigning the ID. Therefore it would not allow me to update as it could no identify which item from the table to update due to not been assigned the ID.

Like so;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM