codeDom codeDom - 1 year ago 57
C# Question

Detect if deleting DataGrid row is valid to delete

I use EF code-first for the datagrid itemsSourse, how can i detect on PreviewKeyUp event if the items the user want to delete is valid to be deleted or not.

For example, if user delete a 'customer', and an 'order' contains customerId it is illegal.
Is there any way to know if the identifier of the item that user want to delete is being used as the foreign key in another table?
Is EF has Any information on it?

Something like that:

private void DataGridEX_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
if (e.Key == Key.Delete) {
if (e.OriginalSource is DataGridCell) {
DataGrid dataGrid = sender;
if (!IsValidToDelete(dataGrid.SelectedCells)) {
e.Handled = true;
MsgBox("Not Valid To Delete !");

Answer Source

It sounds like there's a selected row in the customer grid, and you're evaluating whether or not to delete that selected customer.

And customer and order are both in your EF model.

So get that customer, find his ID, and write a query which checks your order table in the EF model for orders with that customer ID. Here's the idea, semantically -- your actual code will look a bit different, no doubt.

var selCustomerID = (dataGrid.SelectedRow as customer).customerID;
var customerHasOrder = myEFModel.order.Any(ordr => ordr.customerID == selCustomerID);

Think of that Any call as being like a loop that'll call the lambda for each row in myEFModel.order, and return true the first time the lambda returns true.

ordr => ordr.customerID == selCustomerID

In reality, of course, since you're doing LINQ to EF, it's generating a SQL query.