Linq to sql - 删除,如果失败则继续
如果我有一个像这样的表:
StudentId | ... | SchoolId
___________|_____|__________
1 | ... | SchoolA
2 | ... | SchoolA
3 | ... | SchoolB
...
并且我想删除从 schoolA 到 schoolZ 的学校列表(使用 LINQ-to-SQL):
foreach(School s in schools){
db.Schools.DeleteOnSubmit(s);
db.submitChanges();
}
SchoolA
和 SchoolB
将失败,因为上面的 FK 参考资料
我怎样才能继续并删除所有其他学校,并丢弃发生异常的学校?
If I have a table like:
StudentId | ... | SchoolId
___________|_____|__________
1 | ... | SchoolA
2 | ... | SchoolA
3 | ... | SchoolB
...
And I want to delete a list of schools, from schoolA to schoolZ (using LINQ-to-SQL):
foreach(School s in schools){
db.Schools.DeleteOnSubmit(s);
db.submitChanges();
}
SchoolA
and SchoolB
will fail because of the FK references above
How can I continue and delete all other schools, discarding the ones where the exception occurred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
仅包括没有学生的学校:
Only include schools that don't have any students:
默认情况下,LINQ to SQL 在出现第一个错误时失败并回滚事务。如果您希望它继续处理任何可能的事情,您可以在 SubmitChanges 上传递 ConflictMode 重载以允许它继续进行。 “LINQ 实际操作”中的以下示例尝试发出所有排队的更新,然后输出通过处理 ChangeConflictException 遇到的冲突。
当然,最好是积极主动,只尝试删除有效的记录,正如 Mark Cidade 所演示的那样。
By default, LINQ to SQL fails on the first error and rolls back the transaction. If you want it to keep working on anything it can, you can pass in the ConflictMode overload on SubmitChanges to allow it to keep going. The following sample from "LINQ in Action" tries to issue all of the queued updates and then output the conflicts that were encountered by handling the ChangeConflictException.
Naturally, it is much better to be proactive and only try to delete the records that are valid as Mark Cidade demonstrated.
我同意 Mark Cidade 的观点,但我可以建议改进使用联接范围向数据库服务器发送单个请求。
I agree with Mark Cidade, but I can suggest an improvement of using a join scope to send a single request to the database server.
我同意马克的解决方案。如果您不想删除学校及其学生,您可以使用:
这样您就满足了 FK 约束,因此不会引发任何错误。
I agree with Mark's solution. If you wan't to delete the school and its students, you can use:
That way you are fulfilling the FK constraint, so no errors are thrown.
发现了一个简单的方法
Found out a simple way