我有以下代码连接到我的数据库,并检查表中是否存在电子邮件地址,如果存在,它将删除它,如果不存在,它将添加它。
但是这两种选择都不起作用。两种操作都出现相同的错误:
无法删除该对象,因为它在 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;
}