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.
Try adding:
_context.Entry(user).State = EntityState.Modified;
before
_context.SaveChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With