Peter W Smith
Peter W Smith

Reputation: 13

Deleting all records from multiple tables using Entity Framework

I am using Entity Framework, C# 4.0 and Visual Studio 2010. I need to execure a simple SQL query to delete the content of four tables. The query contains:

DELETE FROM dbo.tblMFile
DELETE FROM dbo.tblMContacts
DELETE FROM dbo.tblPersonDetails
DELETE FROM dbo.tblAddresses

There is a foreign key contraint between some of the tables.

There seems to be no simple way to do this.

With reference to my comments on the first respondant's answer:

Upvotes: 1

Views: 1965

Answers (3)

TomTom
TomTom

Reputation: 62137

No, and that is good so. ORM's are not for bulk deletions. If you really want to use LINQ to issue a DELETE, use BlToolkit that allows you to express arbitrary pretty much standard DML non bulk (no truncate) in LINQ.

Delete ALL records?

TRUNCATE TABLE, NOT DELETE.

TRUNCATE TABLE tblMFile

Depending how much the table contains that can be thousands of times faster. Mostly because it does also not log the deleted data - just the fact that a truncate occurred.

Upvotes: 3

Hardeep Singh
Hardeep Singh

Reputation: 866

Try This

_db.ExecuteStoreCommand("delete from MachineMaster where IdMachine =" + obj_Machine.IdMachine + "  or IdMasterMachine=" + obj_Machine.IdMachine  );

Upvotes: 0

cincura.net
cincura.net

Reputation: 4150

To add to the answer from @TomTom. You can't do that directly using Entity Framework. But you can:

  • create a stored procedure to delete the records (it can also take the table name as parameter)
  • use ExecuteStoreQuery see see and write the SQL command directly

Upvotes: 2

Related Questions