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();
}
}
}
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();
You are missing a
db.SubmitChanges();
Since your are not submitting the changes the deletes will never be executed.
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();
}
}
}
精彩评论