hughesdan
hughesdan

Reputation: 2851

Linq-to-Sql Delete Command not Working

Below is a simple Linq-to-SQL query to delete an address record associated with a given user ID. It looks correct to me and matches other examples I've followed on the web. However, when I execute it the record is not deleted. And there is no error message returned. What did I do wrong?

protected void Button1_Click(object sender, EventArgs e)
    {
        int UserID = 250;

        SBMData2.SBMDataContext db = new SBMData2.SBMDataContext();

        var addresses = from a in db.Addresses
                        where a.UserID == UserID
                        select a;

        foreach (var address in addresses)
        {
            try
            {
                db.Addresses.DeleteOnSubmit(address);
            }
            catch (Exception ex)
            {

                Label1.Text = ex.StackTrace.ToString();
            }
        }
    }

Upvotes: 1

Views: 986

Answers (3)

Eric Herlitz
Eric Herlitz

Reputation: 26307

I'd done something like this (untested though)

protected void Button1_Click(object sender, EventArgs e)
{
    int userID = 250;
    SBMData2.SBMDataContext db = new SBMData2.SBMDataContext();

    var addresses = db.Addresses.Where(x => x.UserID == userId);

    foreach (var address in addresses)
    {
        try
        {
            db.Addresses.DeleteOnSubmit(address);
            db.SubmitChanges();
        }
        catch (Exception ex)
        {
            Label1.Text += ex.StackTrace.ToString();
        }
    }
}

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 161012

You are missing a

db.SubmitChanges();

Since your are not submitting the changes the deletes will never be executed.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245519

You haven't submitted any changes in your example. You've only queued the changes to be saved upon submit.

To actually write the changes to the database, you have to call db.SubmitChanges();

Upvotes: 4

Related Questions