asp.net-mvc 使用 LINQ to SQL 从数据库中删除所有记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2515303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete all records from a database using LINQ to SQL
提问by Samir
I am using MVC. How do I delete all records from the database using LINQ to SQL? A code example would be greatly appreciated.
我正在使用MVC。如何使用 LINQ to SQL 从数据库中删除所有记录?一个代码示例将不胜感激。
回答by Brian Mains
If you want to delete all records from a table, you do:
如果要删除表中的所有记录,请执行以下操作:
context.Entities.DeleteAllOnSubmit(dc.Entities);
DeleteAllOnSubmit takes an enumerable collection, and while I haven't tried it, it should support this (as dc.Entities is a Table), which should delete all the entities.
DeleteAllOnSubmit 需要一个可枚举的集合,虽然我还没有尝试过,但它应该支持这个(因为 dc.Entities 是一个表),它应该删除所有实体。
You have to do this for all the tables; you cannot just issue one command to do this. Alternatively, you could create a procedure with all of the deletes and just execute that, by adding the proc to the list of methods.
您必须为所有表执行此操作;你不能只发出一个命令来做到这一点。或者,您可以创建一个包含所有删除的过程,然后通过将 proc 添加到方法列表来执行该过程。
Also, to note, it's faster to drop and recreate the tables in the database than it is to actually perform all those deletes, FYI, if you have a rather large result set in the DB.
另外,请注意,如果数据库中有相当大的结果集,删除和重新创建数据库中的表比实际执行所有这些删除要快,仅供参考。
回答by XpiritO
Considering you're referring to Linq to SQL, I think it is not possible to do what you want (clear all database entities) with just one command line.
考虑到您指的是Linq to SQL,我认为仅用一个命令行是不可能完成您想要的(清除所有数据库实体)的。
You could use SQL truncateor deletecommand to delete each one of your entities, using DataContext.ExecuteCommand, as follows:
您可以使用 SQLtruncate或delete命令删除每个实体,使用DataContext.ExecuteCommand,如下所示:
context.ExecuteCommand("DELETE FROM EntityName");
Or
或者
context.ExecuteCommand("TRUNCATE TABLE EntityName");
Although, you still have to do this for each one of your entities and pay attention to relationships between entities (foreign keys).
尽管如此,您仍然必须为每个实体执行此操作,并注意实体之间的关系(外键)。
Other references:
其他参考:
回答by codymanix
you cannot use linq for that since linq is just a query language and not a data manipulation language. use a dataadapter or createstatement or sql for this task instead.
您不能为此使用 linq,因为 linq 只是一种查询语言而不是数据操作语言。请改用 dataadapter 或 createstatement 或 sql 来执行此任务。

