删除预约记录报错

来源:11-6 【重构】ORM数据管理(下)

rickey_gong

2023-02-01

问题描述:用ORM重构代码后,选中预约记录后点击取消预约,列表不会刷新,我看了老师在视频中的代码和我自己的是一样的,但是老师的却会刷新。然后我在db.SaveChanges()后面添加了customersList_SelectionChanged(null, null);预约列表才会刷新,为什么会这样?
图片描述
删除预约记录代码片段:

        private void DeleteAppointment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var appointmentId = appointmentList.SelectedValue;

                using (AppDbContext db = new())
                {
                    var appointmentToRemove = db.Appointments.Where(a => a.Id == (int)appointmentId).FirstOrDefault();
                    db.Appointments.Remove(appointmentToRemove);
                    db.SaveChanges();
                    //添加刷新预约列表才正常
                    //customersList_SelectionChanged(null, null);
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }

MainWindow.xaml.cs代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using WPF_CMS.Models;

namespace WPF_CMS
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SqlConnection _sqlConnection;
        public MainWindow()
        {
            InitializeComponent();
            string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";

            _sqlConnection = new SqlConnection(connectionString);

            ShowCustomers();
        }

        private void ShowCustomers()
        {
            try
            {
                using (AppDbContext? db = new AppDbContext())
                {
                    List<Customer> customers = db.Customers.ToList();
                    customersList.DisplayMemberPath = "Name";
                    customersList.SelectedValuePath = "Id";
                    customersList.ItemsSource = customers;
                }

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        private void customersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                Customer selectedItem = customersList.SelectedItem as Customer;
                NameTextBox.Text = selectedItem.Name;
                IdTextBox.Text = selectedItem.IdNumber;
                AddressTextBox.Text = selectedItem.Address;

                using (AppDbContext db = new())
                {
                    object customerId = customersList.SelectedValue;
                    List<Appointment> appointment = db.Appointments.Where(a => a.CustomerId == (int)customerId).ToList();

                    appointmentList.DisplayMemberPath = "Time";
                    appointmentList.SelectedValuePath = "Id";
                    appointmentList.ItemsSource = appointment;
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }

        private void DeleteCustomer_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("删除客户");
            try
            {
                string sqlDeleteAppointment = "delete from Appointments where CustomerId = @CustomerId";
                string sqlDeleteCustomer = "delete from Customers where Id = @CustomerId";
                var customerId = customersList.SelectedValue;
                if (customerId == null)
                {
                    if (customerId == null)
                    {
                        MessageBox.Show("请选择需要删除的客户");
                        return;
                    }
                }
                SqlCommand cmd1 = new SqlCommand(sqlDeleteAppointment, _sqlConnection);
                SqlCommand cmd2 = new SqlCommand(sqlDeleteCustomer, _sqlConnection);
                cmd1.Parameters.AddWithValue("@CustomerId", customerId);
                cmd2.Parameters.AddWithValue("@CustomerId", customerId);
                _sqlConnection.Open();
                cmd1.ExecuteScalar();
                cmd2.ExecuteScalar();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                _sqlConnection.Close();
                //刷新客户列表和预约列表
                ShowCustomers();
                customersList_SelectionChanged(null, null);
            }
        }

        private void DeleteAppointment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var appointmentId = appointmentList.SelectedValue;

                using (AppDbContext db = new())
                {
                    var appointmentToRemove = db.Appointments.Where(a => a.Id == (int)appointmentId).FirstOrDefault();
                    db.Appointments.Remove(appointmentToRemove);
                    db.SaveChanges();
                    //添加刷新预约列表才正常
                    //customersList_SelectionChanged(null, null);
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }

        private void AddCustomer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var sql = "insert into Customers values (@Name,@IdNumber,@Address)";
                SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);
                sqlCommand.Parameters.AddWithValue("@Name", NameTextBox.Text);
                sqlCommand.Parameters.AddWithValue("@IdNumber", IdTextBox.Text);
                sqlCommand.Parameters.AddWithValue("@Address", AddressTextBox.Text);
                _sqlConnection.Open();
                sqlCommand.ExecuteScalar();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                _sqlConnection.Close();
                //刷新客户列表
                ShowCustomers();
                //customersList_SelectionChanged(null, null);
            }
        }

        private void AddAppointment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var sql = "insert into Appointments values (@date,@customerId)";
                SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);
                sqlCommand.Parameters.AddWithValue("@date", ApponitmentDatePicker.Text);
                sqlCommand.Parameters.AddWithValue("@customerId", customersList.SelectedValue);
                _sqlConnection.Open();
                sqlCommand.ExecuteScalar();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                _sqlConnection.Close();
                //刷新预约列表
                customersList_SelectionChanged(null, null);
            }
        }

        private void UpdateCustomer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var sql = "update Customers set Name=@name,IdNumber=@idNumber,Address=@address where Id=@customerId";

                SqlCommand sqlCommand = new SqlCommand(sql, _sqlConnection);

                sqlCommand.Parameters.AddWithValue("@name", NameTextBox.Text.Trim());
                sqlCommand.Parameters.AddWithValue("@idNumber", IdTextBox.Text.Trim());
                sqlCommand.Parameters.AddWithValue("@address", AddressTextBox.Text.Trim());
                sqlCommand.Parameters.AddWithValue("@customerId", customersList.SelectedValue);

                _sqlConnection.Open();
                sqlCommand.ExecuteScalar();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
            finally
            {
                _sqlConnection.Close();
                //刷新客户列表
                ShowCustomers();
            }
        }
    }
}

写回答

1回答

慕小白0101

2023-03-09

1.老师的代码里,DeleteAppointment_Click事件try{}catch{}后有个finally{customersList_SelectionChanged(null, null);}

2.第二次点击预约按钮报错是因为参数传空值导致,argumentnullexception指参数为空的异常,Appointments表的项都是设置非空的,你在代码里加个点击取消时的判断就好

1
0

C#速成指南--从入门到进阶,实战WPF与Unity3D开发

系统掌握C#核心和应用,获得全行业适配的技能

870 学习 · 200 问题

查看课程