Delete all entities in Entity Framework

后端 未结 8 1700
天命终不由人
天命终不由人 2020-12-13 17:10

I want to delete content of all tables (all entities) using Entity Framework 4+. How can this be done?

8条回答
  •  一个人的身影
    2020-12-13 17:32

    This will perform much, much better than anything involving deleting individual entity objects, assuming the underlying database is MSSQL.

    foreach (var tableName in listOfTableNames)
    {
        context.ExecuteStoreCommand("TRUNCATE TABLE [" + tableName + "]");
    }
    

    Of course, if your tables have foreign-key relationships, you'll need to set up your list of table names in the proper order so that you clear foreign-key tables before you clear any primary-key tables that they might depend upon.

提交回复
热议问题