How should I remove all elements in a DbSet?

后端 未结 6 977
臣服心动
臣服心动 2020-12-04 21:01

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

6条回答
  •  清歌不尽
    2020-12-04 21:18

    Here's another way you can do it in code.

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

    To actually call the method and clear the set:

    myDbContext.DeleteAll();
    

提交回复
热议问题