Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Sql: How to quickly clear a table

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?

like image 812
Svish Avatar asked Oct 04 '09 17:10

Svish


People also ask

Is LINQ faster than SQL?

More importantly: when it comes to querying databases, LINQ is in most cases a significantly more productive querying language than SQL. Compared to SQL, LINQ is simpler, tidier, and higher-level.

Which one is faster to delete a table in SQL?

On SQL Server you can use the Truncate Table command which is faster than a regular delete and also uses less resources. It will reset any identity fields back to the seed value as well.


2 Answers

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:

  • Batch Updates and Deletes with LINQ to SQL
  • LINQ to SQL Extension: Batch Deletion with Lambda Expression
like image 163
Christian C. Salvadó Avatar answered Oct 18 '22 13:10

Christian C. Salvadó


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.

like image 25
Kirk Broadhurst Avatar answered Oct 18 '22 13:10

Kirk Broadhurst