C# 实体框架4在删除对象时抛出System.Data.UpdateException
我正在使用EF4.0,试图从数据库中删除一条记录,但我的代码不断引发以下异常: “System.Data.UpdateException”类型的首次意外异常 发生在System.Data.Entity.dll中 这是我的密码:C# 实体框架4在删除对象时抛出System.Data.UpdateException,c#,entity-framework,entity-framework-4,C#,Entity Framework,Entity Framework 4,我正在使用EF4.0,试图从数据库中删除一条记录,但我的代码不断引发以下异常: “System.Data.UpdateException”类型的首次意外异常 发生在System.Data.Entity.dll中 这是我的密码: public bool ApproveUser(string username) { using (var context = new UserRegistrationEntities()) { // The entry object
public bool ApproveUser(string username)
{
using (var context = new UserRegistrationEntities())
{
// The entry object gets populated correctly
var entry = context.PendingApprovals
.Where(e => e.Username.Equals(username))
.FirstOrDefault();
try
{
context.DeleteObject(entry);
// Also tried context.PendingApprovals.DeleteObject(entry)
context.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
我已经仔细阅读了代码,异常被抛出到context.SaveChanges()代码>
我遗漏了什么吗?任何帮助都将不胜感激
提前感谢您是否设置了断点并查看条目是否有值?试试这个
public bool ApproveUser(string username)
{
using (var context = new UserRegistrationEntities())
{
// The entry object gets populated correctly
var entry = context.PendingApprovals
.First(e => e.Username.Equals(username))
if (entry != null) {
try
{
context.PendingApprovals.DeleteObject(entry);
context.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
return false;
}
请先尝试删除它:
public bool ApproveUser(string username)
{
using (var context = new UserRegistrationEntities())
{
// The entry object gets populated correctly
var entry = context.PendingApprovals
.Where(e => e.Username.Equals(username))
.FirstOrDefault();
try
{
context.PendingApprovals.Remove(entry);
context.DeleteObject(entry);
// Also tried context.PendingApprovals.DeleteObject(entry)
context.SaveChanges();
return true;
}
catch
{
return false;
}
}
}
您是否绝对确定已正确填充条目
FirstOrDefault
可能正在创建一个集合中不存在的新对象。@klugerama我100%确定。所有条目
的字段都与我的数据库表中的记录匹配。