views:

1954

answers:

1

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?

+12  A: 

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:

CMS
make sure to fix the word "DELETE"
David
I +1'd this. Here's a reference explaining the difference between Truncate (which I think you want to do), and Delete:http://www.mssqltips.com/tip.asp?tip=1080
David
+1 on David's comment: truncate may be *a lot* faster than delete
Fredrik Mörk
actually you might have to worry about this as well:http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/e21ec1b7-4468-4a37-84e1-3d6a79e58c6b
David
@David: That problem is specific to the Entity Framework (*Linq-to-Entities*), I have used `TRUNCATE` before without problems on Linq-to-SQL
CMS
How would you use Truncate? `context.ExecuteCommand("TRUNCATE Entity");`, or something?
Svish
CMS, yeah, I just caught that (I use EF now). In EF you can use something like _db.DeleteObject(obj); for *one* obj.
David
@Svish: context.ExecuteCommand("TRUNCATE TABLE Entity");
marc_s
marc_s is right, here's the full grammar:TRUNCATE TABLE [ { database_name.[ schema_name ]. | schema_name . } ] table_name[ ; ]
David
Cool. Guess I will create a truncate extension method then :)
Svish
How can I get the name of a table?
Svish
Figured it out :)
Svish
Truncate requires more rights than the normal writer rights required for a DELETE :)
Snake