0

データベースに接続する次のコードがあり、メールアドレスがテーブルに存在するかどうかを確認し、存在する場合は削除し、存在しない場合は追加します。

しかし、どちらのオプションも機能しません。両方のアクションで同じエラーが発生します。

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;
}
4

1 に答える 1

1

You need to attach before you delete

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

but you probably want to select the existing item more like this

Newsletter newsletter = database.Newsletters.FirstOrDefault(nl => nl.EmailAddress == emailAddress);
if (newsletter == null)
{
    newsletter = new Newsletter();
    ...
}
else
{
    database.Attach(newsletter); 
    database.DeleteObject(newsletter); 
    database.SaveChanges(); 
}
于 2012-07-25T11:36:07.653 に答える