开发者

EF4 circular reference problem when deleting

开发者 https://www.devze.com 2023-02-06 01:47 出处:网络
Hi I am using EF 4 self tracking entities. I have three tables (Questionnaire, Section and Page) as follows;

Hi I am using EF 4 self tracking entities. I have three tables (Questionnaire, Section and Page) as follows;

Questionnaire
Id
Title
WhenClosedShowPageId

Section
Id
QuestionnaireId

Page
Id
SectionId

So that in the EF model Questionnaire has Sections and Section has Pages. WhenClosedShowPageId is a nullable int that references the page to show when the questionnaire is closed. All references have associations to maintain referential integrity.

The problem comes when I mark all entities as deleted and attempt to save. If WhenClosedShowPageId was null when I retrieved the data, then the delete works fine. If WhenClosedShowPageId is set to a value then EF cannot work out the order in which to delete. This is understandable. However if I set WhenClosedShowPageId to null, mark the entities as deleted and save, the same thing happens. I would have expected EF to generate an update statement first to set WhenClosedShowPageId to null on the database and then for it to delete the entities.

The only w开发者_JAVA百科ay I can see to get around the issue is to do two independent saves myself, the first to set WhenClosedShowPageId to null and the second to delete the entities. This is a heavily layered app though and I don't want to have to create a special case just for this.

Is there any way around this?

Darren


Entity Framework will discard pending edits if an entity has been flagged for deletion. After all, if you're getting rid of it, what's the sense in updating the data first? Unfortunately, this can lead to the very condition you're seeing.

The best solution to your problem would be to make both ends of the association through WhenClosedShowPageId not cascade the deletion (End1 OnDelete and End2 OnDelete set to None). Since that page is part of a section that's part of the Questionnaire, it will ultimately be deleted anyway, so you don't need to worry about it.

0

精彩评论

暂无评论...
验证码 换一张
取 消