95

To delete all the rows in a table, I am currently doing the following:

context.Entities.DeleteAllOnSubmit(context.Entities);
context.SubmitChanges();

However, this seems to be taking ages. Is there a faster way?

Sam
  • 7,252
  • 16
  • 46
  • 65
Svish
  • 152,914
  • 173
  • 462
  • 620

5 Answers5

135

You could do a normal SQL truncate or delete command, using the DataContext.ExecuteCommand method:

context.ExecuteCommand("DELETE FROM Entity");

Or

context.ExecuteCommand("TRUNCATE TABLE Entity");

The way you are deleting is taking long because Linq to SQL generates a DELETE statement for each entity, there are other type-safe approaches to do batch deletes/updates, check the following articles:

shox
  • 677
  • 1
  • 5
  • 19
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • make sure to fix the word "DELETE" – David Oct 04 '09 at 17:51
  • 12
    I +1'd this. Here's a reference explaining the difference between Truncate (which I think you want to do), and Delete: http://www.mssqltips.com/tip.asp?tip=1080 – David Oct 04 '09 at 17:55
  • 1
    +1 on David's comment: truncate may be *a lot* faster than delete – Fredrik Mörk Oct 04 '09 at 17:56
  • actually you might have to worry about this as well: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/e21ec1b7-4468-4a37-84e1-3d6a79e58c6b – David Oct 04 '09 at 17:56
  • 1
    @David: That problem is specific to the Entity Framework (*Linq-to-Entities*), I have used `TRUNCATE` before without problems on Linq-to-SQL – Christian C. Salvadó Oct 04 '09 at 18:05
  • How would you use Truncate? `context.ExecuteCommand("TRUNCATE Entity");`, or something? – Svish Oct 04 '09 at 18:11
  • CMS, yeah, I just caught that (I use EF now). In EF you can use something like _db.DeleteObject(obj); for *one* obj. – David Oct 04 '09 at 18:13
  • marc_s is right, here's the full grammar: TRUNCATE TABLE [ { database_name.[ schema_name ]. | schema_name . } ] table_name [ ; ] – David Oct 04 '09 at 18:16
  • Cool. Guess I will create a truncate extension method then :) – Svish Oct 04 '09 at 19:20
  • Truncate requires more rights than the normal writer rights required for a DELETE :) – Anemoia Sep 03 '10 at 09:22
  • 1
    TRUNCATE will clear out any auto indexing that has been established (typically an Id column) so be careful if you do not want that to reset. DELETE FROM will not. – JCisar Nov 07 '16 at 23:05
22

Unfortunately LINQ-to-SQL doesn't execute set based queries very well.

You would assume that

context.Entities.DeleteAllOnSubmit(context.Entities); 
context.SubmitChanges(); 

will translate to something like

DELETE FROM [Entities]

but unfortunately it's more like

DELETE FROM [dbo].[Entities] WHERE ([EntitiesId] = @p0) AND ([Column1] = @p1) ...
DELETE FROM [dbo].[Entities] WHERE ([EntitiesId] = @p0) AND ([Column1] = @p1) ...
DELETE FROM [dbo].[Entities] WHERE ([EntitiesId] = @p0) AND ([Column1] = @p1) ...

You'll find the same when you try to do bulk update in LINQ-to-SQL. Any more than a few hundred rows at a time and it's simply going to be too slow.

If you need to do batch operations & you're using LINQ-to-SQL, you need to write stored procedures.

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169
13

I like using an Extension Method, per the following:

public static class LinqExtension
{
  public static void Truncate<TEntity>(this Table<TEntity> table) where TEntity : class
  {
    var rowType = table.GetType().GetGenericArguments()[0];
    var tableName = table.Context.Mapping.GetTable(rowType).TableName;
    var sqlCommand = String.Format("TRUNCATE TABLE {0}", tableName);
    table.Context.ExecuteCommand(sqlCommand);
  }
}
Bill Roberts
  • 1,127
  • 18
  • 30
0

you could also use this:

Public void BorraFilasTabla()
{
 using(basededatos db = new basededatos())
 {
  var ListaParaBorrar = db.Tabla.Tolist();
  db.Tabla.RemoveRange(ListaParaBorrar); 
 }
}
-1

The Below c# code is used to Insert/Update/Delete/DeleteAll on a database table using LINQ to SQL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace PracticeApp
{
    class PracticeApp
    {        
        public void InsertRecord(string Name, string Dept) {
            LinqToSQLDataContext LTDT = new LinqToSQLDataContext();
            LINQTOSQL0 L0 = new LINQTOSQL0 { NAME = Name, DEPARTMENT = Dept };
            LTDT.LINQTOSQL0s.InsertOnSubmit(L0);
            LTDT.SubmitChanges();
        }

        public void UpdateRecord(int ID, string Name, string Dept)
        {
            LinqToSQLDataContext LTDT = new LinqToSQLDataContext();
            LINQTOSQL0 L0 = (from item in LTDT.LINQTOSQL0s where item.ID == ID select item).FirstOrDefault();
            L0.NAME = Name;
            L0.DEPARTMENT = Dept;
            LTDT.SubmitChanges();
        }

        public void DeleteRecord(int ID)
        {
            LinqToSQLDataContext LTDT = new LinqToSQLDataContext();
            LINQTOSQL0 L0;
            if (ID != 0)
            {
                L0 = (from item in LTDT.LINQTOSQL0s where item.ID == ID select item).FirstOrDefault();
                LTDT.LINQTOSQL0s.DeleteOnSubmit(L0);
            }
            else
            {
                IEnumerable<LINQTOSQL0> Data = from item in LTDT.LINQTOSQL0s where item.ID !=0 select item;
                LTDT.LINQTOSQL0s.DeleteAllOnSubmit(Data);
            }           
            LTDT.SubmitChanges();
        }

        static void Main(string[] args) {
            Console.Write("* Enter Comma Separated Values to Insert Records\n* To Delete a Record Enter 'Delete' or To Update the Record Enter 'Update' Then Enter the Values\n* Dont Pass ID While Inserting Record.\n* To Delete All Records Pass 0 as Parameter for Delete.\n");
            var message = "Successfully Completed";
            try
            {
                PracticeApp pa = new PracticeApp();
                var enteredValue = Console.ReadLine();                
                if (Regex.Split(enteredValue, ",")[0] == "Delete") 
                {
                    Console.Write("Delete Operation in Progress...\n");
                    pa.DeleteRecord(Int32.Parse(Regex.Split(enteredValue, ",")[1]));
                }
                else if (Regex.Split(enteredValue, ",")[0] == "Update")
                {
                    Console.Write("Update Operation in Progress...\n");
                    pa.UpdateRecord(Int32.Parse(Regex.Split(enteredValue, ",")[1]), Regex.Split(enteredValue, ",")[2], Regex.Split(enteredValue, ",")[3]);
                }
                else
                {
                    Console.Write("Insert Operation in Progress...\n");
                    pa.InsertRecord(Regex.Split(enteredValue, ",")[0], Regex.Split(enteredValue, ",")[1]);
                }                                
            }
            catch (Exception ex)
            {
                message = ex.ToString();
            }
            Console.Write(message);            
            Console.ReadLine();                        
        }
    }
}