EntityState.Deleted does not work, Remove(entity) does?

走远了吗. 提交于 2019-12-01 06:06:16

Remove will also remove the child objects, but using Deleted will not. You should really be using Remove for this very reason. If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place).

1.) What is the difference and best times to use .Remove() vs .Deleted?

It appears that setting the entity's state to Deleted causes SaveChanges() to delete only that specific entity from the database, not taking into account other rows that may reference it via a non-null foreign-key column.

Remove() will take into account rows that are part of the relationship.

2.) How could I make this work using the .Deleted method?

If you have ON CASCADE DELETE behavior specified for the related rows, the database should handle it automatically. This is the default behavior when you let EF generate the database.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!