tags:

views:

28

answers:

1

Being new to Linq-to-SQL, I ran into one of it's Gotchas today and I wanted to share my solution and then ask if there was something better.

I'm setting up a staff allocation tool for my work. There are three basic class/tables: Employee, Project, Assignment. Importantly here, Assignment serves as a junction table between Employee and Project. I ran into my problem on a form that contained a DataGridView that was bound to a BindingList. The problem came when a user decided to create a new assignment, but then before saving their changes they decided to delete the new assignment that they had just created. Unfortunately, saving caused the deleted assignment to be saved anyhow!

Here is a (somewhat simplified) version of my naive delete handler:

//Assume that assignments is the BindingList<Assignment> bound
//to the dataGridView
private void DeletedRowHandler(object sender, EventArgs e)
{
    DataGridViewRow row = dataGridView.GetSelectedRow();
    Assignment assignment = (Assignment) row.DataBoundItem();
    assignments.Remove(assignment);

    try
    {
        db.Intervals.DeleteOnSubmit(assignment);
    }
    catch
    {
    }

}    

After much weeping and gnashing of teeth, it occurred to me that through the magic if Linq-to-SQL, the Employee and Project which the deleted assignment had been associated with already had a reference to the Assignment that I thought I was deleting. This was causing it to be submitted to the database eventually.

The fix that I ended up using was to insert the following code in my delete handler:

assignment.Employee = null;
assignment.Project = null;

This appears to work.

My question: Is this what you're supposed to do? Or is there a cleaner approach that I don't know about?

Note: In writing this question I got a friendly, automated notice that this question was likely going to be closed. If you decide to close it, then please be kind enough to tell me why and to point me in a good direction.

A: 

Suggest deleting by ID, if you can. Let the DataContext find the entity by its key, and supply that entity to the Delete method.

DeleteAssignment(someRowID);

...
public void DeleteAssignment(int assignmentID)
{
    db.Assignments.DeleteOnSubmit(
       db.Assignments.SingleOrDefault(a=>a.ID==assignmentID)
    );
    db.SubmitChanges();
}
p.campbell