Delete Multiple Rows in Linq to SQL
-
Friday, February 29, 2008 5:00 PMI am trying to use linq to delete rows from SQL Server database.
var something = (from inv in InventoryLTD
where inv.rate == 1000I tried the following
select inv)
foreach (var detail in something)
{
db.INVENTORYLTD.DeleteOnSubmit(detail);
}
db.SubmitChanges();
and
db.INVENTORYLTD.DeleteAllOnSubmit(something);
db.SubmitChanges();
both of them only help me to delete one row from the table, but var something should have at least 100 rows .
Can someone tell me why ?
Thanks
Answers
-
Monday, March 03, 2008 8:42 PM
Well, It wasn't as easy as it seemed, but here it is,
My "multiple delete" is called like this:
Code Snippetprivate void btnDeleteSales_Click(object sender, EventArgs e)
{
using (MyLibraryDataContext dc = new MyLibraryDataContext())
{
dc.DeleteAll(dc.Books.Where(b => b.AuthorId == author.AuthorId &&
b.Title.StartsWith("[SALE]")));
}
}
Note that the "DeleteAll" function can receive any IQueryable, which should be obtained from the same DataContext where the DeleteAll is been invoked, but this is not defensively checked.
An follwing is the extension method to the DataContext class, it uses some Regex to change:
"SELECT .......... FROM table as t1 WHERE ............ t1.Field = ........ t1.Field2 > ........"
into:
"DELETE .......... FROM table WHERE ............ table.Field = ........ table.Field2 > ........"
Note that some extra work is needed because "AS" is not allowed in the FROM clause on sql DELETE operations.Code Snippetusing
System;using
System.Collections.Generic;using
System.Linq;using
System.Text;using
System.Data.Linq;using
System.Text.RegularExpressions;using
System.Data.Common;namespace
MyLibrary{
public static class LinqExtensions{
public static int DeleteAll(this DataContext dc, IQueryable collection){
DbCommand comm = dc.GetCommand(collection); Regex selectRE = new Regex("^SELECT[\\s]*(?<Fields>.*)[\\s]*FROM[\\s]*(?<Table>.*)[\\s]*AS[\\s]*(?<TableAlias>.*)[\\s]*WHERE[\\s]*(?<Condition>.*)", RegexOptions.IgnoreCase); Match m = selectRE.Match(comm.CommandText); if (!m.Success)
throw new ArgumentException("Cannot delete this type of collection"); string table = m.Groups["Table"].Value.Trim(); string tableAlias = m.Groups["TableAlias"].Value.Trim(); string condition = m.Groups["Condition"].Value.Trim().Replace(tableAlias,table);comm.CommandText = string.Format("DELETE FROM {0} WHERE {1}", table, condition);
if (comm.Connection.State != System.Data.ConnectionState.Open)
comm.Connection.Open();
return comm.ExecuteNonQuery();
}
}
}

