Entity Framework 5 Remove() not deleting from the database
Solution 1
Try adding:
_context.Entry(user).State = EntityState.Modified;
before
_context.SaveChanges();
Solution 2
I used the same answer as @tomsullivan1989 but with 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
Solution 3
My suggestion would be to try using a profiling tool (e.g. EFprof from hibernating rhino's, which has a free trial).
It will show you exactly what SQL EF generated, so you can watch what happens as you step past SaveChanges.
It does sound odd, perhaps there's some silent SQL error that's being thrown that a profiler may reveal.
Related videos on Youtube
John Mc
Updated on September 15, 2022Comments
-
John Mc over 1 year
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.
-
Panagiotis Kanavos over 10 yearsHave you opened a transaction outside your Delete method? The entity won't be deleted from the database until you commit the transaction. Other queries that use the same context will not see the deleted
User
because the context has the entity marked asdeleted
-
CodeCaster over 10 years"it is not being deleted from the Database. Strangely enough, my queries for retrieving Users no longer return it though." - then analyze that. Do you use a custom
DbContext
that for example sets aDeleted
flag instead of hard-deleting rows? How do you query for the user and why doesn't that return it if the row still exists? Does your application use the same connection string as you when checking the database? -
John Mc over 10 yearsThere is no error or exception. Everything seems like it works until I check the DB and see that the record still exists
-
Slauma over 10 yearsBut "my queries for retrieving Users no longer return it though" does not mean that you can reboot your computer, that the user is still in the database and that you run a query for this user with no result, or does it?
-