使用ADO.NET删除DB条目

时间:2012-07-25 11:33:23

标签: c# .net database entity-framework 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 个答案:

答案 0 :(得分: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(); 
}