我正在使用EF4.0而我正在尝试从数据库中删除记录,但我的代码仍然抛出以下异常:
类型'System.Data.UpdateException'的第一次机会异常 发生在System.Data.Entity.dll
中
这是我的代码:
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();
我错过了什么吗?任何帮助将不胜感激!
提前致谢
答案 0 :(得分:0)
您是否设置了断点并查看条目是否有值?试试这个?
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;
}
答案 1 :(得分:0)
首先尝试删除它:
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;
}
}
}