我正在使用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();
我有遗漏什么吗?任何帮助都将不胜感激!
提前感谢
发布于 2013-10-01 23:03:46
您是否设置了断点并查看条目是否有值?尝尝这个?
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;
}发布于 2013-10-01 23:10:06
先试着移除它:
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;
}
}
}https://stackoverflow.com/questions/19126939
复制相似问题