Microsoft 9GD00001 Manuel D’Utilisation

Page de 449
 
Chapter 7:  Working with Data 
213
    Customer firstCust = customers.SingleOrDefault(); 
 
    if (firstCust != null) 
    { 
        myShop.Customers.DeleteOnSubmit(firstCust); 
    } 
 
    myShop.SubmitChanges(); 
}
VB:
Sub DeleteCustomer(ByVal custID As Integer) 
    Dim myShop As New MyShopDataContext 
 
    Dim customers = 
        From cust In myShop.Customers 
        Where cust.CustomerID = custID 
        Select cust 
 
    Dim firstCust As Customer = 
        customers.SingleOrDefault() 
 
    If (firstCust IsNot Nothing) Then 
        myShop.Customers.DeleteOnSubmit(firstCust) 
    End If 
 
    myShop.SubmitChanges() 
End Sub
This example is similar to the update example that did a query and then a call to 
SingleOrDefault
 to get a reference to the requested object. You then use the collection 
property, Customers in this case, to call the DeleteOnSubmit method. You need the 
check for null (Nothing in VB), or you’ll receive an ArgumentNullException when 
DeleteOnSubmit
 executes and the firstCust argument is null (Nothing in VB). Remember 
to call SubmitChanges; otherwise, you won’t delete the record.
A final note on the preceding three sections. The code runs in an insert, update, and 
delete sequence. Notice how the insert methods return an int, which is the CustomerID. 
Whenever you perform a query from a database, you’ll often want to get the ID field for 
the record at the same time. The reason is that the ID is unique to that one record and 
you can perform subsequent actions with the ID. Both the update and delete methods in 
preceding examples accepted an int parameter that was used to perform a database lookup 
of the record. Again, using the ID guarantees that we’ll only return one record, which is 
also why I was confident in calling SingleOrDefault. Since this chapter is about data, I 
purposely don’t show you how the program handles that ID. However, you’ll see IDs being