首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体框架4在删除对象时抛出System.Data.UpdateException

实体框架4在删除对象时抛出System.Data.UpdateException
EN

Stack Overflow用户
提问于 2013-10-01 22:16:52
回答 2查看 852关注 0票数 0

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

System.Data.UpdateException类型的第一次例外发生在System.Data.Entity.dll中

这是我的密码:

代码语言:javascript
复制
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();

我有遗漏什么吗?任何帮助都将不胜感激!

提前感谢

EN

回答 2

Stack Overflow用户

发布于 2013-10-01 23:03:46

您是否设置了断点并查看条目是否有值?尝尝这个?

代码语言:javascript
复制
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;
}
票数 0
EN

Stack Overflow用户

发布于 2013-10-01 23:10:06

先试着移除它:

代码语言:javascript
复制
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;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19126939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档