删除对象时,Entity Framework 4会抛出System.Data.UpdateException

时间:2013-10-01 22:16:52

标签: 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 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();

处抛出异常

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

提前致谢

2 个答案:

答案 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;
        }
    }
}
相关问题