public static class DbContextExtensions { public static void DeleteBatch<T>(this DbContext context, IQueryable<T> query) where T : class { string sqlClause = GetClause<T>(query); context.Database.ExecuteSqlCommand(String.Format("DELETE {0}", sqlClause)); } private static string GetClause<T>(IQueryable<T> clause) where T : class { string snippet = "FROM [dbo].["; string sql = clause.ToString(); string sqlFirstPart = sql.Substring(sql.IndexOf(snippet)); sqlFirstPart = sqlFirstPart.Replace("AS [Extent1]", ""); sqlFirstPart = sqlFirstPart.Replace("[Extent1].", ""); return sqlFirstPart; } }
简单调用
context.DeleteBatch(context.People.Where(p => p.Name == "Jim"));