Gehad
Gehad

Reputation: 17

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint using ExecuteSqlCommand

i want to clear data from this table from entity framework

db2.Database.ExecuteSqlCommand("TRUNCATE TABLE [destDepartments]");

but i have this error

Cannot truncate table 'destDepartments' because it is being referenced by a FOREIGN KEY constraint.'

so how i can do this from EF?

Upvotes: 0

Views: 2288

Answers (2)

cf_en
cf_en

Reputation: 1661

There are restrictions on when you can use TRUNCATE TABLE. One of them is that the table cannot be involved in foreign key relationships with other tables in the database. Use DELETE FROM [destDepartments] instead.

TRUNCATE TABLE and DELETE FROM are not functionally equivalent but the latter will allow you to clear a table that is related to other tables in the database (provided referential integrity is maintained).

Upvotes: 2

Callam Woolgar
Callam Woolgar

Reputation: 1

Make sure to get rid of any references before deleting the table.

Upvotes: 0

Related Questions