WCF and LINQ to SQL (Part 3 (Deletes))

If you’ve read parts 1 and 2 you’ll know we’ve covered the CR of CRUD, today we will cover the ‘D’ – deletions. We’ll need to update our interface to actually provide this functionality:

[ServiceContract]
public interface ICarsService
{
    [OperationContract]
    Car GetCar(int id);
 
    [OperationContract]
    void SubmitCar(Car car);
 
    [OperationContract]
    void DeleteCar(int id);
}

I’ve decided to delete the car via the identifier we created initially, though there is nothing to stop us using a ‘Car’ instance.

Anyhews, so, let’s code this up:

public void DeleteCar(int id)
{
    var car = GetCar(id);
    if(car == null)
        throw new ArgumentException("Car unknown!");
 
    _db.Cars.DeleteOnSubmit(car);
    _db.SubmitChanges();
}

Right, to perform a deletion we need the car instance, so we can just get that from our current library code. So… let’s test this bad boy… Remember to ‘Update’ our service reference…

UpdateServiceReference

So, we’ll use the following code:

CarsServiceClient client = new CarsServiceClient();
var car6 = client.GetCar(6);
client.DeleteCar(car6.ID);

(of course this does rely on you having a car with an id of ‘6’ in your db)

Once you’ve got this working (i.e. you have a valid car id) you’ll hit this problem:

SqlException_FK Foreign key constraints!! How do we get around this?

Well, we need to delete the owner first (and whilst we’re at it, the ‘PreviousOwners'), so let’s update the code:

public void DeleteCar(int id)
{
    var car = GetCar(id);
    if(car == null)
        throw new ArgumentException("Car unknown!");
 
    _db.Owners.DeleteOnSubmit(car.Owner);
    foreach (var owner in car.PreviousOwners)
        _db.PreviousOwners.DeleteOnSubmit(owner);
 
    _db.Cars.DeleteOnSubmit(car);
    _db.SubmitChanges();
}

Now when we run the code, we succeed!

There is another way to do the deletion, and that’s to write a stored proc that does the deletion in the correct order, and then, in the CarsDataContext edit the ‘DeleteCar’ method to call the stored proc instead. But I’ll leave that to you :)

So… All that’s left is the Update part of CRUD… and hopefully I’ll get that done soon!

Cheers!

Print | posted @ Tuesday, April 7, 2009 5:00 PM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: