如何使用LINQ-TO-SQL基于非主键字段项的集合删除多行?

时间:2022-03-24 04:39:36

I have this columns,

我有这个专栏,

id int primary key,
code int not null

I want to delete all items where code equals to one of the items in a,

我想删除所有代码等于a中的一个项目的项目,

IEnumerable<int> someEnumerable

One possible way is using iteration. But I want to do it without explicit iteration (for, foreach). Another way is by doing this:

一种可能的方法是使用迭代。但我想在没有明确迭代的情况下做到这一点(for,foreach)。另一种方法是这样做:

var result = db.table.Where(a => someEnumerable.Contains(a.code));
db.table.DeleteAllOnSubmit(result);
db.SubmitChanges();

But for me it causes:

但对我来说,它会导致:

An unhandled exception of type 'System.*Exception' occurred in System.Data.Linq.dll

System.Data.Linq.dll中发生了未处理的“System.*Exception”类型异常

2 个解决方案

#1


As stated here it was caused by a Linq bug, corrected on .NET 4.0

如上所述,它是由一个Linq错误引起的,在.NET 4.0上得到纠正

Contains now detects self-referencing IQueryable and doesn't cause a stack overflow

Contains现在检测自引用IQueryable并且不会导致堆栈溢出

From somewhere in SO:

来自SO的某个地方:

In .NET 3.5 to solve the problem: When using 'Auto Generated Value' = True, then you must set 'Delay Loaded' to False - otherwise you get the recursion error.

在.NET 3.5中解决问题:当使用'Auto Generated Value'= True时,必须将'Delay Loaded'设置为False - 否则会出现递归错误。

#2


It looks to me like the code you have should work. You might want to try and narrow down whether the exception is coming from the selection of the entities or the actual deletion. Try adding a ToList() to the query, which will force it to run the selection logic, then see if the exception is thrown during the selection or on the delete.

它看起来像你应该工作的代码。您可能希望尝试缩小异常是来自实体的选择还是实际删除。尝试向查询添加ToList(),这将强制它运行选择逻辑,然后查看在选择期间或删除时是否抛出异常。

#1


As stated here it was caused by a Linq bug, corrected on .NET 4.0

如上所述,它是由一个Linq错误引起的,在.NET 4.0上得到纠正

Contains now detects self-referencing IQueryable and doesn't cause a stack overflow

Contains现在检测自引用IQueryable并且不会导致堆栈溢出

From somewhere in SO:

来自SO的某个地方:

In .NET 3.5 to solve the problem: When using 'Auto Generated Value' = True, then you must set 'Delay Loaded' to False - otherwise you get the recursion error.

在.NET 3.5中解决问题:当使用'Auto Generated Value'= True时,必须将'Delay Loaded'设置为False - 否则会出现递归错误。

#2


It looks to me like the code you have should work. You might want to try and narrow down whether the exception is coming from the selection of the entities or the actual deletion. Try adding a ToList() to the query, which will force it to run the selection logic, then see if the exception is thrown during the selection or on the delete.

它看起来像你应该工作的代码。您可能希望尝试缩小异常是来自实体的选择还是实际删除。尝试向查询添加ToList(),这将强制它运行选择逻辑,然后查看在选择期间或删除时是否抛出异常。