Linq to Sql: How to quickly clear a table

C#Linq to-SqlDelete Row

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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:

Solution 2 - C#

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.

Solution 3 - C#

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);
  }
}

Solution 4 - C#

you could also use this:

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

Solution 5 - C#

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();                        
        }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSvishView Question on Stackoverflow
Solution 1 - C#Christian C. SalvadóView Answer on Stackoverflow
Solution 2 - C#Kirk BroadhurstView Answer on Stackoverflow
Solution 3 - C#Bill RobertsView Answer on Stackoverflow
Solution 4 - C#Gerardo GuajardoView Answer on Stackoverflow
Solution 5 - C#user5222219View Answer on Stackoverflow