Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

P.S 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.

like image 490
John Mc Avatar asked Aug 21 '13 12:08

John Mc


1 Answers

Try adding:

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

before

_context.SaveChanges();
like image 200
tomsullivan1989 Avatar answered Nov 02 '22 09:11

tomsullivan1989