2
DELETE From Table
WHERE ID in (1,2,3, ... )

Is there any way to produce following query in LINQ? I tried RemoveRange, but from SQL Server Profiler find that it actually deletes records separately

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
DVL
  • 180
  • 2
  • 11

3 Answers3

1

You could first define the item(s) to remove, then iterate over the list removing them one by one: (note that the whole operation has to be done inside database context scope otherwise it won't work)

var toRemove = list.Where(l => l.id == 1 || l.id == 2 || l.id == 3);
foreach (var item in toRemove)
{
    databasecontext.table.Remove(item);      //replace databasecontext.table with your own context and table name
}
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41
-1

You can write it in single line

table.RemoveAll(tbl => tbl.id == 1 || tbl.id == 2 || tbl.id == 3);

Hope this helps.

Sridhar
  • 55
  • 5
-1

Try this piece of code to make this, It will work for you.

DataContextClass _DbContext = new DataContextClass();
var remove = _DbContext.tableName.where(x=>x.id >= 1 && x.id <= endValue);
if(remove != null)
{
     db.logins.RemoveRange(remove);
     db.SaveChanges();
}
  • This doesn't answer the question. This also "actually deletes records separately". – Gert Arnold Apr 12 '22 at 15:33
  • @GertArnold it's working on my side. – Qais Ali Abbas Apr 20 '22 at 12:21
  • Then this is not Entity Framework (or LINQ-to-SQL, as in the question) but another ORM you didn't mention. The point here is how to prevent multiple delete statements like `DELETE xx WHERE Id = yy` even when they occur by one SaveChanges call. – Gert Arnold Apr 20 '22 at 12:29