简体   繁体   中英

Entity framework - remove related records by id

Okay. assume I have structure:

School -> students -> StudentParents <- parents -> address

School can have many students, students can be relatives and have the same set of parents (may-to-many). Each parent can have multiple addresses.
Assume that students who have the same set of parents cannot study in different schools.

If given school_Id =5, I want to remove this school and all related records. How to do this easily in Entity Framework 4?

Answer for your question would be same as this question .

You are trying to solve the problem in the wrong layer. You need to reconsider your database design specially how you maintain the referential integrity.

You need to set the "CASCADE DELETE"s of the foreign keys and reflect that in your Entity Model. Then the database will make the necessary changes to maintain the referential integrity when you delete that entity.

Entity framework cannot delete data from database that is not instantiated as object in memory. This means you would need to load school data, all students data, all students parent data and so on, and then you would need to manually delete all the data.

This seems like a lot of work to do, so you may want to take another approach to this problem - delete all this data using stored procedure on database that is mapped to ObjectContext , this would perform better since you would not need to get all the data into memory.

But this also seems troublesome. The best approach would be to create Cascade delete constrain on database and map it also in entity framework's model. This has two advantages - you would need to only load school data and after it is deleted from model, it would be deleted from database and cascade delete would remove all referencing data. But if you have school and students data already in memory, EF will take care of marking those objects from memory as deleted, which will make your data consistent with database state.

The best resolution to this problem depends on whether you may or may not modify database. If you can - go for cascade delete . If you cannot - I would recommend stored procedure approach as better performing (assuming performance is an issue and there is lots of students, parents etc. in database).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM