提交之前删除新子记录时的 Linq-to-sql 错误
我有两个具有主从关系的表。我们使用 DataGridView 来处理详细记录。详细记录的字段带有查找值(外键)。我们设置对象值,而不是设置查找表的 ID 值。这一切都运作良好,而不是一种情况。如果我们添加详细信息行并设置至少一个查找字段并在保存(提交更改)之前删除该行,我们会收到此错误:
尝试删除 TableX 和 TableY 之间的关系。但是,关系的外键之一 (TableY.TableXID) 不能设置为 null。
这个问题在这个问题中讨论过(向下滚动Neil Barnwell 的回答),但它没有解决这个特定问题的答案。解决方案“Call Datacontext.GetChanges”没有帮助,因为 Datacontext 没有公开 GetChanges 方法,并且 GetChangedset 失败并出现相同的错误。
I have 2 tables with a master-detail relationship. We use a DataGridView to handle the detail records. The detail records have fields with lookup values (foreign keys). Instead of setting the ID value of the lookup tables we set the object value. This all works well, instead of one situation. If we add a detail row and set at least one of the lookup fields and remove this row before saving (submitchanges), we receive this error:
An attempt was made to remove a relationship between a TableX and a TableY. However, one of the relationship's foreign keys (TableY.TableXID) cannot be set to null.
This problem was discussed in this question (scroll down to answer of Neil Barnwell), but it doesn't have an answer for this particular problem. The solution "Call Datacontext.GetChanges" doesn't help as Datacontext doesnt expose a method GetChanges and GetChangedset fails with same error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为删除该行时存在某种错误。当您将详细信息行添加到主行时,它会自动附加到上下文。因此,如果您添加:
您必须使用
DeleteOnSubmit
来反转添加:数据上下文足够智能,可以将删除视为“撤消添加”,因此该条目永远不会到达数据库。
I assume there is some kind of mistake when removing the row. When you add the detail row to the master row, it is automatically attached to the context. So if you add with:
You have to use
DeleteOnSubmit
to reverse the adding:The data context is smart enough to treat the deletion as "undo add", so the entry will never hit the database.
看起来,如果您设置实体的对象并在任何提交之前删除新记录,Linq 仍然认为您要添加新记录。在这种情况下,您必须将所有具有 FK 引用的对象设置为 null。
请参阅这篇文章,其中详细描述了问题和解决方案:http://social.msdn.microsoft.com/Forums/en/linqtosql/thread/4170c7bb-f727-4e6a-9190-fc268ae4ce4b
It seems that if you set an object of the entity and remove the new record before any submit Linq still thinks you want to add the new record. In this case you have to set all objects that have FK references to null.
See this post which describes the problem and solution in detail: http://social.msdn.microsoft.com/Forums/en/linqtosql/thread/4170c7bb-f727-4e6a-9190-fc268ae4ce4b