我该如何删除DbSet中的所有元素?

时间:2012-05-04 12:17:30

标签: c# .net entity-framework-4

使用Entity Framework 4.3删除System.Data.Entity.DbSet中所有元素的最佳方法是什么?

8 个答案:

答案 0 :(得分:96)

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

(不开玩笑。)

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

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

或者避免加载完整实体可能要便宜一点:

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();

但在这两种情况下,您都需要加载所有实体或所有键属性,并从集合中逐个删除实体。此外,当您调用SaveChanges时,EF会将n(=集合中的实体数量)DELETE语句发送到数据库,该数据库也会在数据库中逐个执行(在单个事务中)。

因此,直接SQL显然更适用于此目的,因为您只需要一个DELETE语句。

答案 1 :(得分:14)

以下是您在代码中执行此操作的另一种方式。

public static class Extensions
{
    public static void DeleteAll<T>(this DbContext context)
        where T : class
    {
        foreach (var p in context.Set<T>())
        {
            context.Entry(p).State = EntityState.Deleted;
        }
    }
}

要实际调用该方法并清除该组:

myDbContext.DeleteAll<MyPocoClassName>();

答案 2 :(得分:13)

旧帖子,但现在有一个RemoveRange方法:

    dbContext.MyEntities.RemoveRange(dbContext.MyEntities);
    dbContext.SaveChanges();

答案 3 :(得分:3)

如果您要删除所有元素而不编写任何SQL ,只执行单Db调用

Entity Framework Extended Library提供批量删除方法。

context.Users.Delete();

答案 4 :(得分:2)

由于接受的答案仅提及以下方法:

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

而是提供替代方案,我已经设法编写了一个方法,您可以使用该方法来避免加载所有实体,然后循环遍历它们并使用 ExecuteSqlCommand

假设使用工作单元,其中上下文是DbContext:

using System.Data.Entity.Core.Objects;
using System.Text.RegularExpressions;

public void DeleteAll()
{
    ObjectContext objectContext = ( (IObjectContextAdapter)context ).ObjectContext;
    string sql = objectContext.CreateObjectSet<T>().ToTraceString();
    Regex regex = new Regex( "FROM (?<table>.*) AS" );
    Match match = regex.Match( sql );
    string tableName = match.Groups[ "table" ].Value;

    context.Database.ExecuteSqlCommand( string.Format( "delete from {0}", tableName ) );
}

第一个代码块检索 ExecuteSqlCommand 方法中所需的表名。

用法:

using ( var context = new UnitOfWork() )
{
    context.MyRepository.DeleteAll();
}

无需致电

context.SaveChanges()

答案 5 :(得分:1)

如果您正在使用工作单元和通用存储库,则可以找到以下有用的

public virtual void DeleteWhere(Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;
            if (filter != null)
            {
                query = query.Where(filter);
            }
            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            foreach (var entity in query)
            {
                context.Entry(entity).State = EntityState.Deleted;
            }
        }

用法:

uow.myRepositoryName.DeleteWhere(u => u.RoomId == roomId);
uow.Save();

答案 6 :(得分:0)

您可以使用直接查询来实现它:

32 Bit Mode

答案 7 :(得分:0)

使用存储库模式,您可以在其中为存储库指定模型类型,并且它可以处理任何模型类型。

    public async Task<int> RemoveAllAsync()
    {
        Context.Set<T>().RemoveRange(await Context.Set<T>().ToListAsync());
        return await Context.SaveChangesAsync();
    }