BLACK JACK

Get busy living, or get busy dying.
posts - 25, comments - 186, trackbacks - 30, articles - 2

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

Posted on 2008-03-07 18:53 J. Lin 阅读(2704) 评论(5)  编辑 收藏 网摘 所属分类: Linq to SQL

前些天看了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

Feedback

#1楼   回复  引用  查看    

2008-03-07 21:32 by GoKu'S Blog      
这样搞..还不如直接写sql语句...

#2楼   回复  引用  查看    

2008-03-07 22:45 by Jeffrey Zhao      
哈,很好,其实我刚想写些,呵呵。
还有不会有什么UpdateProvider,DeleteProvider的,LINQ的Q就是Query,不是用来Delete和Update的——标准操作里没有这个东西。
所以LINQ再扩展也做不到用LINQ来删除等等,呵呵。

#3楼   回复  引用  查看    

2008-05-29 02:38 by 小No      
其实DeleteAll整个方法的代码跟思路都是Benjamin Eidelman写的

根本不是楼主原创~~~

我觉得用别人的东西就应该注明,应该尊重别人的劳动~~~
不要拿别人的东西装高手~~

原帖:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2929114&SiteID=1" target="_new">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2929114&SiteID=1

#4楼   回复  引用    

2009-04-18 23:13 by 楼上好强[未注册用户]
这都被你挖出来了。佩服。



发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 1095602




相关文章:

相关链接: