LINQ to SQL刪除實現(xiàn)體會小結
在實現(xiàn)LINQ to SQL刪除時可以使用Lambda Expression批量刪除數(shù)據那么在解析表達式過程中生成Where Condition會有大量的代碼生成,那么這里向你做一點簡單的總結,算是一點體會吧,希望對你有所幫助。
根據LINQ to Sql原有的設計,解析Query得到DbCommand應該是SqlProvider干的事,只是現(xiàn)在這個SqlProvider只從IReaderProvider出(事實上MS也沒設計個IUpdateProvider或者IDeleteProvider來著),所以也只對SELECT感冒。搞的咱們只能在DataContext里自力更生了。
LINQ to SQL刪除實現(xiàn)的實例:
不過既然已經有了可以生成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
LINQ to SQL刪除的目標:
- 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語句,增加判斷必不可少。
LINQ to SQL刪除最終完成如下:
- 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
原文來自博客園:http://www.cnblogs.com/jackielin/archive/2008/03/07/1095602.html
LINQ to SQL刪除的實現(xiàn)過程中的一點體會就向你介紹到這里,希望對你了解和學習LINQ to SQL刪除有所幫助。
【編輯推薦】