如何在linq中删除pk是另一个fk的记录
我的数据库具有这样的字段
CId(PK- Auto Generated)
IsSub(bit)
PId(FK)
:在此结构中,Cid 是自动生成的,如果新记录是 cid 的子记录,则 Issub=true,并且 Pid= Cid 的 id。
现在,当我想删除没有子元素的记录时,它可以完美工作。 但如果有嵌套记录,那么它会显示错误。
如何删除具有嵌套记录的记录。 CID IsSub PID
1 FALSE null
2 FALSE null
3 TRUE 2
4 TRUE 2
在上面我如何删除 CID=2 ?
我的代码是 v
ar del = context.DataTable.Where(c => c.CId == userData.CId).Single();
context.DataTable.DeleteObject(del);
context.SaveChanges();
这将删除不包含任何引用键的单个记录。 我该怎么做才能删除两者 1)删除cid=1
或删除cid=2,也会删除cid=3和4。
My database having fields like
CId(PK- Auto Generated)
IsSub(bit)
PId(FK)
In this structure, Cid is auto generated and if new record is child record of cid the Issub=true, and Pid= id of Cid.
Now when i want to delete record that having no child elements it works perfect.
but if there is nested records then it will show me an error.
How can do deletion of that record having nested records.
CID IsSub PID
1 FALSE null
2 FALSE null
3 TRUE 2
4 TRUE 2
In above how can i delete CID=2 ?
My Code is
v
ar del = context.DataTable.Where(c => c.CId == userData.CId).Single();
context.DataTable.DeleteObject(del);
context.SaveChanges();
This will delete single record that do not holding any reference key.
what can i do to delete both
1) delete cid=1
or to delete cid=2, will delete cid=3 and 4 also.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Linq2SQL 没有固有的级联删除功能 - 您需要自己完成这项工作。一些想法此处和此处。
Linq2SQL doesn't have an inherent cascading delete capability - you will need to do the work yourself. Some ideas here and here.
创建 fk 时,您可以指定在删除父记录或引发异常时是否应自动删除子记录。
您的外键显然引发了异常。
存在三种可能的解决方案:
更改外键以便删除子记录。 (显然,您的数据库中缺少此功能)
在删除父记录之前手动删除子记录。
在删除父记录之前,将子记录的父记录设置为 null(或父记录的父记录)。
When you create the fk you can specify whether it should delete child record automatically when the parent is deleted or raise an exception.
Your foreign key obviously raises an exception.
There are three possible solutions:
Change the foreign key so that it deletes the child record. (apparently, this feature is missing in your database)
Manually delete the child records before deleting the parent.
Set the parent of the child record to null (or to the parent of the parent) before deleting the parent.