2009-10-04 15 views
77

Para eliminar todas las filas de una tabla, estoy haciendo actualmente los siguientes:LINQ to SQL: Cómo borrar rápidamente una tabla

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

Sin embargo, esto parece estar tomando las edades. ¿Hay una manera mas rápida?

+0

¿Alguna razón por la que no está utilizando un proceso almacenado para una eliminación más rápida y segura? Puede hacer que el proc se asigne a dbml – Perpetualcoder

+1

¿No sería necesario crear uno para cada tabla, entonces? ¿O? – Svish

Respuesta

108

Usted podría hacer un truncado SQL normal o eliminar comandos, utilizando el DataContext.ExecuteCommand método:

context.ExecuteCommand("DELETE FROM Entity"); 

O

context.ExecuteCommand("TRUNCATE TABLE Entity"); 

La forma en que va a eliminar es tomar mucho tiempo porque LINQ a SQL genera un DELETE declaración para cada entidad, hay otros tipos seguro enfoques para hacer eliminaciones/actualizaciones por lotes, consulte los artículos siguientes:

+0

asegúrese de corregir la palabra "ELIMINAR" – David

+9

I + 1 en esto. Aquí hay una referencia que explica la diferencia entre Truncate (que creo que desea hacer) y Delete: http://www.mssqltips.com/tip.asp?tip=1080 – David

+1

+1 en el comentario de David: truncado puede ser * mucho * más rápido que eliminar –

20

Desafortunadamente LINQ a SQL no ejecuta consultas basadas conjunto muy bien.

Se podría asumir que

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

se traducirá en algo así como

DELETE FROM [Entities] 

pero desafortunadamente es más como

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) ... 

Encontrará lo mismo cuando se trata de hacer actualización masiva en LINQ-to-SQL. Más de unos cientos de filas a la vez y simplemente será demasiado lento.

Si necesita hacer operaciones por lotes & está utilizando LINQ-to-SQL, debe escribir procedimientos almacenados.

11

me gusta usar un método de extensión, por el siguiente:

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

el siguiente código C# se utiliza para insertar/actualizar/borrar/ElimTodo en una tabla de base de datos utilizando 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();       
     } 
    } 
} 
+0

agregar alguna explicación –