Are you trying to remove an entry directly from the DBSet? In that case, EntityState will be set to Deleted. But if you are trying to remove an entry in another list in DBSet with a foreign key, then the foreign key will be set to null (if your database allows nulls), resulting in the status of parent DBSet to be Modified and not Deleted.
Entitystate is set to modified instead of Delete
-
03-08-2022 - |
Question
I am removing an item from the following List
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
cities.Remove(2);
The context keeps track of this delete.
var entityChangeList = ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);
return entityChangeList.Count();
Although entityChangeList.Count() is 1, EntityState is modified. As per my understanding it must be deleted. Should I manually set the state to deleted?
Thanks
Solution
OTHER TIPS
you should not manually set the state unless you want to override the behaviour. If you call the Remove method, EF should set the state by itself. see the example below
var itemToRemove = Get(id, context);
var result = context.Set<T>().Remove(itemToRemove);
context.SaveChanges();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow