简体   繁体   English

实体框架5 Remove()不能从数据库中删除

[英]Entity Framework 5 Remove() not deleting from the database

I have a User object and when it is deleted using Remove() on the DbContext, it is not being deleted from the Database. 我有一个User对象,当使用DbContext上的Remove()删除它时,它没有从数据库中删除。 Strangely enough, my queries for retrieving Users no longer return it though. 奇怪的是,我用于检索用户的查询不再返回。

This code is used through my application and works for other entities without any problems. 此代码可在我的应用程序中使用,并且可以毫无问题地用于其他实体。

I'd really appreciate suggestions as to what this could be, as I'm stumped! 我很感激关于这可能是什么的建议,因为我很困惑!

#region Delete
    public virtual void Delete(User entity)
    {
        var user = _context.Users.FirstOrDefault(u => u.UserId == entity.UserId);
        if (user != null)
        {
            user.Roles.Clear();
            var actionHistories = _context.ActionHistories.Where(u => u.User.UserId == user.UserId);
            foreach (var actionHistory in actionHistories)
            {
                _context.ActionHistories.Remove(actionHistory);
            }
            _context.Users.Remove(user);

            _context.SaveChanges();
        }
    }
    #endregion

PS The code for removing Roles and ActionHistories was added by me to test if the problem was with related entities existing, but it did not fix the problem. PS我删除了删除Roles和ActionHistories的代码,以测试问题是否出在相关实体的存在,但是它不能解决问题。

Try adding: 尝试添加:

_context.Entry(user).State = EntityState.Modified;

before 之前

_context.SaveChanges();

I used the same answer as @tomsullivan1989 but with EntityState.Deleted; 我使用与@ tomsullivan1989相同的答案,但使用EntityState.Deleted;。 and it solved my similar problem. 它解决了我类似的问题。 Which had error message The relationship could not be changed because one or more of the foreign-key properties is non-nullable 出现错误消息的关系无法更改,因为一个或多个外键属性不可为空

My suggestion would be to try using a profiling tool (eg EFprof from hibernating rhino's, which has a free trial). 我的建议是尝试使用配置文件工具(例如,从休眠犀牛的EFprof中免费试用)。

It will show you exactly what SQL EF generated, so you can watch what happens as you step past SaveChanges. 它会准确显示SQL EF生成的内容,因此您可以观察经过SaveChanges时发生的情况。

It does sound odd, perhaps there's some silent SQL error that's being thrown that a profiler may reveal. 听起来确实很奇怪,也许正在抛出探查器可能揭示的一些静默SQL错误。

The Problem is the "Virtual" _context you must delete in main Context in this Case Like this 问题是在这种情况下必须在主上下文中删除“虚拟” _context

Database.Context.Remove<ActionHistories>(actionHistory); 

Then save Changes in Main Context 然后在主上下文中保存更改

Database.Context.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM