Removing all records from a database using LINQ to SQL

I am using MVC. How to delete all records from a database using LINQ to SQL? Sample code is welcome.

+4
source share
3 answers

If you want to delete all records from the table, follow these steps:

context.Entities.DeleteAllOnSubmit(dc.Entities); 

DeleteAllOnSubmit accepts an enumerated collection, and while I have not tried it, it must support this (since dc.Entities is a table), which should delete all entities.

You must do this for all tables; you cannot just issue one command for this. In addition, you can create a procedure with all deletions and simply execute it by adding proc to the list of methods.

In addition, it should be noted that it is faster to roll back and recreate tables in the database than to actually perform all these deletions, FYI, if you have a fairly large result installed in the database.

+6
source

Given that you are referencing Linq to SQL , I think it is impossible to do what you want (clear all database objects), only one command line.

You can use the SQL truncate or delete command to delete each of your objects using DataContext.ExecuteCommand , as follows:

 context.ExecuteCommand("DELETE FROM EntityName"); 

or

 context.ExecuteCommand("TRUNCATE TABLE EntityName"); 

Although you still need to do this for each of your entities and pay attention to the relationships between entities (foreign keys).

Other links:

+7
source

you cannot use linq for this, since linq is just a query language, not a data processing language. instead, use this dataadapter or createstatement or sql command instead.

0
source

Source: https://habr.com/ru/post/1305088/


All Articles