BLACK JACK

Get busy living, or get busy dying.

导航

Linq to Sql: 批量删除之投机取巧版

Posted on 2008-03-07 18:53  J. Lin  阅读(7615)  评论(6编辑  收藏  举报

前些天看了Jeffrey扩展LINQ to SQL:使用Lambda Expression批量删除数据。说实话解析表达式生成Where Condition的那部分代码基本没看懂(事实是代码太多实在是没耐心看)。

根据Linq to Sql原有的设计,解析Query得到DbCommand应该是SqlProvider干的事,只是现在这个SqlProvider只从IReaderProvider出(事实上MS也没设计个IUpdateProvider或者IDeleteProvider来着),所以也只对SELECT感冒。搞的咱们只能在DataContext里自力更生了。

不过既然已经有了可以生成SELECT的IReaderProvider,稍微把SELECT语句改造一下不就能得到DELETE了吗!基本思路:

        public static int DeleteAll<TEntity>(this Table<TEntity> table, Expression<Func<TEntity, bool>> predicate)
           
where TEntity : class
       
{
           
IQueryable query = table.Where(predicate);
           
DbCommand com = dc.GetCommand(query);

            //TODO:改造sql语句

            return com.ExecuteNonQuery();
         }
    }

这里直接拿直接拿where生成的query来GetCommand,得到的sql语句大致如下:

SELECT fields... FROM tableName AS TableAlias WHERE Condition

 

我们的目标是改造成:

DELETE FROM tableName WHERE Condition

 

可见关键是得到tableName,用正则是首选。不过这里还有一个缺陷就是只能用expression来做删除不能用linq query,比如我想这样:

            var query = from item in context.Items
                       
where item.Name.StartsWith("XX")
                       
select item;
            context.DeleteAll(query);

看来要把DeleteAll放到DataContext里,不过这样有风险,有可能会接受到无法转换的SELECT语句,增加判断必不可少。

最终完成如下:

    public static class DataContextEx
    {
        public static int DeleteAll(this DataContext dc, IQueryable query)
        {
            DbCommand com = dc.GetCommand(query);

            Regex reg = new Regex("^SELECT[\\s]*(?<Fields>.*)[\\s]*FROM[\\s]*(?<Table>.*)[\\s]*AS[\\s]*(?<TableAlias>.*)[\\s]*WHERE[\\s]*(?<Condition>.*)",
                                    RegexOptions.IgnoreCase);

            Match match = reg.Match(com.CommandText);

            if (!match.Success)
                throw new ArgumentException("Cannot delete this type of collection");

            string table = match.Groups["Table"].Value.Trim();
            string tableAlias = match.Groups["TableAlias"].Value.Trim();
            string condition = match.Groups["Condition"].Value.Trim().Replace(tableAlias, table);

            com.CommandText = string.Format("DELETE FROM {0} WHERE {1}", table, condition);

            if (com.Connection.State != System.Data.ConnectionState.Open)
                com.Connection.Open();

            return com.ExecuteNonQuery();
        }


        public static int DeleteAll<TEntity>(this Table<TEntity> table, Expression<Func<TEntity, bool>> predicate)
            where TEntity : class
        {
            IQueryable query = table.Where(predicate);

            return table.Context.DeleteAll(query);
        }
    }


 

注:reg表达式取自MSDN Forum