문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top