看了 http://www.cnblogs.com/jinzhao/archive/2013/05/31/3108755.html 这篇文章,但不知道我
dbSet的Delete方法用不了,求指教。
PS, 用foreach Remove方法就别试了,数据量少没问题,数据多了,就麻烦了。所以这种是放弃的。
以下我的拓展
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"));