2011-09-12 60 views
1

下面是一個簡單的Linq-to-SQL查詢,用於刪除與給定用戶ID關聯的地址記錄。它看起來是正確的,並匹配我在網上跟蹤的其他示例。但是,當我執行它時,記錄不會被刪除。並沒有返回錯誤消息。我做錯了什麼?Linq-to-Sql刪除命令不起作用

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(); 
      } 
     } 
    } 

回答

4

您還沒有在您的示例中提交任何更改。您只能在提交時排隊更改以保存。

實際編寫的對數據庫的修改,你必須調用db.SubmitChanges();

3

你缺少一個

db.SubmitChanges(); 

由於您沒有提交刪除將永遠不會被執行的變化。

0

我會做這樣的事情(雖然未經測試)

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(); 
     } 
    } 
}