Entity Framework 5 Remove() not deleting from the database

.net c# entity-framework

Question

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.

1
10
8/21/2013 3:25:00 PM

Popular Answer

Try adding:

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

before

_context.SaveChanges();
5
8/21/2013 3:19:12 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow