简体   繁体   中英

How to delete multiple rows based on a collection of non-primary key field items using LINQ-TO-SQL?

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,

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:

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.StackOverflowException' occurred in System.Data.Linq.dll

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

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

From somewhere in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM