2012-07-25 183 views
0

我有以下代碼連接到我的數據庫,並檢查電子郵件地址是否存在於表中,如果存在,它將刪除它,如果沒有,它將添加它。使用ADO.NET刪除數據庫條目

但這兩個選項都不起作用。我得到了兩個動作相同的錯誤:

對象不能被刪除,因爲它沒有在 ObjectStateManager找到。

代碼:

protected OEntities database = new OEntities(); 

public string NewsletterSubscriptionValidation(string emailAddress) 
{ 
    string validationMessage = ""; 
    Newsletter newsletter = new Newsletter(); 

    var identifier = database.Newsletters.Select(
     id => id.EmailAddress); 

    if (identifier == null) 
    { 
     newsletter.EmailAddress = emailAddress; 
     newsletter.Subscribed = true; 

     database.Newsletters.AddObject(newsletter); 
     database.SaveChanges(); 

     validationMessage = "You are now subscribed to our periodic Newsletter."; 
    } 
    else 
    { 
     newsletter.EmailAddress = emailAddress; 
     newsletter.Subscribed = false; 


     database.DeleteObject(newsletter); 
     database.SaveChanges(); 

     validationMessage = "You have been unsubscribed from our periodic Newsletter."; 
    } 

    return validationMessage; 
} 

難道我甚至增加/刪除數據庫中的正確方法,在這裏?

解決方案


protected OEntities database = new OEntities(); 

public string NewsletterSubscriptionValidation(string emailAddress) 
{ 
    string validationMessage = ""; 
    Newsletter newsletter = database.Newsletters.FirstOrDefault(
     nl => nl.EmailAddress == emailAddress); 

    if (newsletter == null) 
    { 
     newsletter = new Newsletter(); 

     newsletter.EmailAddress = emailAddress; 
     newsletter.Subscribed = true; 

     database.AddToNewsletters(newsletter); 
     //database.Newsletters.AddObject(newsletter); 
     database.SaveChanges(); 

     validationMessage = "You are now subscribed to our periodic Newsletter."; 
    } 
    else 
    { 
     newsletter.EmailAddress = emailAddress; 
     newsletter.Subscribed = true; 

     database.AddToNewsletters(newsletter); 
     //database.Newsletters.AddObject(newsletter); 
     database.SaveChanges(); 

     validationMessage = "You have been unsubscribed from our periodi Newsletter."; 
    } 

    return validationMessage; 
} 

回答

1

您需要刪除

database.Attach(newsletter); 
    database.DeleteObject(newsletter); 
    database.SaveChanges(); 

之前附加,但你可能想選擇現有的資料更多類似這樣

Newsletter newsletter = database.Newsletters.FirstOrDefault(nl => nl.EmailAddress == emailAddress); 
if (newsletter == null) 
{ 
    newsletter = new Newsletter(); 
    ... 
} 
else 
{ 
    database.Attach(newsletter); 
    database.DeleteObject(newsletter); 
    database.SaveChanges(); 
} 
+0

「附加」 - 哦謝謝。非常感謝:-)我會嘗試一下吧! – Arrow 2012-07-25 11:37:51

+0

對不起,但沒有工作。它說:'一個EntityKey值爲null的對象不能附加到對象上下文中。' – Arrow 2012-07-25 11:39:58

+1

請參閱上面的編輯... – podiluska 2012-07-25 11:45:34

相關問題