删除时EF4循环引用问题
您好,我正在使用 EF 4 自跟踪实体。我有三个表格(调查问卷、部分和页面)如下;
Questionnaire
Id
Title
WhenClosedShowPageId
Section
Id
QuestionnaireId
Page
Id
SectionId
因此,在 EF 模型中,调查问卷有部分,部分有页面。 WhenClosedShowPageId 是一个可以为 null 的 int,它引用调查问卷关闭时要显示的页面。所有引用都具有关联以保持引用完整性。
当我将所有实体标记为已删除并尝试保存时,问题就出现了。如果当我检索数据时 WhenClosedShowPageId 为 null,则删除工作正常。如果 WhenClosedShowPageId 设置为一个值,则 EF 无法计算出删除的顺序。这是可以理解的。但是,如果我将 WhenClosedShowPageId 设置为 null,将实体标记为已删除并保存,则会发生相同的情况。我希望 EF 首先生成一条更新语句,将数据库上的 WhenClosedShowPageId 设置为 null,然后删除实体。
我认为解决该问题的唯一方法是自己进行两次独立的保存,第一个将 WhenClosedShowPageId 设置为 null,第二个删除实体。不过,这是一个层次丰富的应用程序,我不想为此创建一个特殊情况。
有什么办法解决这个问题吗?
达伦
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 way 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果实体已被标记为删除,实体框架将放弃挂起的编辑。毕竟,如果您要摆脱它,那么首先更新数据有什么意义呢?不幸的是,这可能会导致您所看到的情况。
解决您的问题的最佳方法是通过 WhenClosedShowPageId 使关联的两端不级联删除(
End1 OnDelete
和End2 OnDelete
设置为None
)。由于该页面是调查问卷的一部分的一部分,因此它最终会被删除,因此您无需担心。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
andEnd2 OnDelete
set toNone
). 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.