我应该怎样删除一个DbSet所有元素? [英] How should I remove all elements in a DbSet?

查看:1339
本文介绍了我应该怎样删除一个DbSet所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是删除一个System.Data.Entity.DbSet的所有元素,与实体框架4.3?

最好的方法
解决方案

  dbContext.Database.ExecuteSqlCommand(删除的MyTable);
 

(别开玩笑。)

问题是,EF不支持任何批处理命令,并使用没有直接的DML会删除一组的所有实体的唯一方法:

 的foreach(在dbContext.MyEntities VAR实体)
    dbContext.MyEntities.Remove(实体);
dbContext.SaveChanges();
 

或许豆蔻便宜一点,以避免加载完整的实体:

 的foreach(在dbContext.MyEntities.Select(E =&GT VAR ID; e.Id))
{
    VAR实体=新myEntity所{n = ID};
    dbContext.MyEntities.Attach(实体);
    dbContext.MyEntities.Remove(实体);
}
dbContext.SaveChanges();
 

但在这两种情况下,你必须加载所有的实体或所有键属性,并通过一个来自集删除实体之一。此外,当你调用的SaveChanges EF将发送N(=实体的集合号)DELETE语句,这也得到了DB逐条执行数据库(在一个单一的交易)。

所以,直接的SQL显然是preferable为了这个目的,你只需要一个DELETE语句。

What's the best way to remove all elements in a System.Data.Entity.DbSet, with Entity Framework 4.3?

解决方案

dbContext.Database.ExecuteSqlCommand("delete from MyTable");

(No kidding.)

The problem is that EF doesn't support any batch commands and the only way to delete all entities in a set using no direct DML would be:

foreach (var entity in dbContext.MyEntities)
    dbContext.MyEntities.Remove(entity);
dbContext.SaveChanges();

Or maybe a litte bit cheaper to avoid loading full entities:

foreach (var id in dbContext.MyEntities.Select(e => e.Id))
{
    var entity = new MyEntity { Id = id };
    dbContext.MyEntities.Attach(entity);
    dbContext.MyEntities.Remove(entity);
}
dbContext.SaveChanges();

But in both cases you have to load all entities or all key properties and remove the entities one by one from the set. Moreover when you call SaveChanges EF will send n (=number of entities in the set) DELETE statements to the database which also get executed one by one in the DB (in a single transaction).

So, direct SQL is clearly preferable for this purpose as you only need a single DELETE statement.

这篇关于我应该怎样删除一个DbSet所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆