0

我正在使用 EF4.0,我正在尝试从数据库中删除一条记录,但我的代码不断抛出以下异常:

System.Data.Entity.dll 中出现“System.Data.UpdateException”类型的第一次机会异常

这是我的代码:

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();

我错过了什么吗?任何帮助将非常感激!

提前致谢

4

2 回答 2

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;
        }
    }
}
于 2013-10-01T23:10:06.223 回答
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;
}
于 2013-10-01T23:03:46.573 回答