private void DeleteCustomer_Click(object sender, RoutedEventArgs e)
{
try
{
var customerId = customerList.SelectedValue;
using (var db = new AppDbContext())
{
var customerToRemove=db.Customers.Include(c=>c.Appointments).Where(c=> c.Id==(int)customerId).FirstOrDefault();
db.Customers.Remove(customerToRemove);
db.SaveChanges();
}
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
finally
{
ShowCustomers();
}
}
代码如上。
在AppDbContext.cs文件中没有找到Ondelete,但是在删除是还是报错,即可以删除没有预约的客户,但是在删除有预约的客户的就会报异常。
异常原因如下:
SqlException: Cannot insert the value NULL into column ‘CustomerId’, table ‘master.dbo.Appointments’; column does not allow nulls. UPDATE fails.
The statement has been terminated.
打了断点,发现就是DeleteCustomer_Click内部报错。