2009-10-04 4 views
77

Per eliminare tutte le righe di una tabella, Attualmente sto facendo la seguente:LINQ to SQL: Come eliminare rapidamente un tavolo

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

Tuttavia, questo sembra prendere le età. C'è un modo più veloce?

+0

Qualche ragione per cui non stai usando un proc di Stored per una cancellazione più veloce e più sicura? Puoi avere il proc mappato su dbml – Perpetualcoder

+1

Non dovresti crearne uno per ogni tabella? O? – Svish

risposta

108

Si potrebbe fare un normale troncare SQL o comando di eliminare, utilizzando il metodo DataContext.ExecuteCommand:

context.ExecuteCommand("DELETE FROM Entity"); 

O

context.ExecuteCommand("TRUNCATE TABLE Entity"); 

Il modo in cui si sta eliminando sta prendendo tempo perché LINQ to SQL genera un DELETE dichiarazione per ogni entità, sono disponibili altri tipi di protezione per eseguire eliminazioni/aggiornamenti batch, controllare i seguenti articoli:

+0

assicurati di correggere la parola "DELETE" – David

+9

Ho fatto +1 su questo. Ecco un riferimento che spiega la differenza tra Truncate (che penso che tu voglia fare) e Elimina: http://www.mssqltips.com/tip.asp?tip=1080 – David

+1

+1 sul commento di David: truncate may be * molto * più veloce di eliminare –

20

Purtroppo LINQ to SQL non esegue le query basate set molto bene.

Si potrebbe supporre che

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

si tradurrà in qualcosa di simile a

DELETE FROM [Entities] 

ma purtroppo è più come

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

Troverete lo stesso quando si tenta di fare aggiornamento collettivo in LINQ-to-SQL. Più di qualche centinaio di file alla volta e sarà semplicemente troppo lento.

Se è necessario eseguire operazioni batch & si utilizza LINQ-to-SQL, è necessario scrivere stored procedure.

11

Mi piace usare un metodo di estensione, per il seguente:

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

Il sotto il codice C# è usato per inserimento/aggiornamento/eliminazione/CancTutti su una tabella di database utilizzando 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

aggiungere qualche spiegazione –