Linq to Sql:如何快速清除表


87

要删除表中的所有行,我目前正在执行以下操作:

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

但是,这似乎需要很长时间。有没有更快的方法?


您是否出于某种原因不使用Stored proc来进行更快更安全的删除?您可以将proc映射到dbml
Perpetualcoder

1
那您不必为每个桌子做一个吗?要么?
Svish

Answers:


125

您可以使用DataContext.ExecuteCommand方法执行普通的SQL截断或删除命令:

context.ExecuteCommand("DELETE FROM Entity");

要么

context.ExecuteCommand("TRUNCATE TABLE Entity");

由于Linq to SQL会为每个实体生成DELETE语句,因此删除的方式花费了很长时间,还有其他类型安全的方法可以进行批量删除/更新,请查看以下文章:


确保修正“删除”一词
大卫,2009年

9
我为此+1了。以下是解释“截断”(我想您想做)和“删除”之间的区别的参考:mssqltips.com/tip.asp?tip=1080
David

1
+1大卫的评论:截断可能是很多不是删除更快
弗雷德里克·莫克

1
@David:这个问题是特定于实体框架(Linq-to-Entities)的,我TRUNCATE之前在Linq-to-SQL上使用时没有问题
Christian C.Salvadó09年

1
TRUNCATE将清除所有已建立的自动索引(通常是一个Id列),因此,如果您不想重置该索引,请小心。DELETE FROM不会。
JCisar '16

20

不幸的是,LINQ-to-SQL不能很好地执行基于集合的查询。

你会认为

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

会翻译成类似

DELETE FROM [Entities]

但不幸的是,它更像

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

当您尝试在LINQ-to-SQL中进行批量更新时,会发现相同的内容。一次只有几百行,这太慢了。

如果您需要执行批处理操作并且您正在使用LINQ-to-SQL,则需要编写存储过程。


12

我喜欢按以下方式使用扩展方法:

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

您还可以使用以下代码:

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

问题是:“有更快的方法吗?”。怎么会更快呢?而且,这不是LINQ to SQL。
Gert Arnold

-1

下面的c#代码用于使用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();                        
        }
    }
}

1
添加一些说明
Yahya Hussein '18
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.