EF架構~性能高效的批量操作(Insert篇)

無論是linq to sql 還是entity frameworks,在進行列表操作時都會有一個毛病,那就是它的操作只能一個實體一個實體的發到服務器,這樣,如果列表的數量很大,如列表爲10萬條數據,那麼,這種操作將是非常性能的,可能你的DB就掛了。

解決方案:拼接T—SQL串,並使它具有通用性

好處:與服務器建立一次連接,給服務器發一條SQL命令,即可實現

代碼如下:

複製代碼
 1   /// <summary>
 2         /// 構建Insert語句串
 3         /// 主鍵爲自增時,如果主鍵值爲0,我們將主鍵插入到SQL串中
 4         /// </summary>
 5         /// <typeparam name="TEntity"></typeparam>
 6         /// <param name="entity"></param>
 7         /// <returns></returns>
 8         private Tuple<string, object[]> CreateInsertSQL<TEntity>(TEntity entity) where TEntity : class
 9         {
10             if (entity == null)
11                 throw new ArgumentException("The database entity can not be null.");
12 
13             Type entityType = entity.GetType();
14             var table = entityType.GetProperties().Where(i => i.PropertyType != typeof(EntityKey)
15                && i.PropertyType != typeof(EntityState)
16                && i.GetValue(entity, null) != null
17                && (i.PropertyType.IsValueType || i.PropertyType == typeof(string)))
18                .ToArray();//過濾主鍵,航行屬性,狀態屬性等
19             List<string> pkList = GetPrimaryKey<TEntity>().Select(i => i.Name).ToList();
20 
21             List<object> arguments = new List<object>();
22             StringBuilder fieldbuilder = new StringBuilder();
23             StringBuilder valuebuilder = new StringBuilder();
24 
25             fieldbuilder.Append(" INSERT INTO " + string.Format("[{0}]", entityType.Name) + " (");
26 
27             foreach (var member in table)
28             {
29                 if (pkList.Contains(member.Name) && Convert.ToString(member.GetValue(entity, null)) == "0")
30                     continue;
31                 object value = member.GetValue(entity, null);
32                 if (value != null)
33                 {
34                     if (arguments.Count != 0)
35                     {
36                         fieldbuilder.Append(", ");
37                         valuebuilder.Append(", ");
38                     }
39 
40                     fieldbuilder.Append(member.Name);
41                     if (member.PropertyType == typeof(string) || member.PropertyType == typeof(DateTime))
42                         valuebuilder.Append("'{" + arguments.Count + "}'");
43                     else
44                         valuebuilder.Append("{" + arguments.Count + "}");
45                     if (value.GetType() == typeof(string))
46                         value = value.ToString().Replace("'", "char(39)");
47                     arguments.Add(value);
48 
49                 }
50             }
51 
52 
53             fieldbuilder.Append(") Values (");
54 
55             fieldbuilder.Append(valuebuilder.ToString());
56             fieldbuilder.Append(");");
57             return new Tuple<string, object[]>(fieldbuilder.ToString(), arguments.ToArray());
58         }
複製代碼

之後我將陸續把更新操作與刪除操作及對增刪改操作進行封裝,

對於EF架構中的批量更新操作,需要我們爲實體的導航屬性進行手動的標示,因爲EF生成的實體中沒有一個特殊的說明,所以,我們必須要告訴系統,哪個屬性是導航屬性,而導航屬性是我們不去進行update的。

複製代碼
1    /// <summary>
2     /// 屬性的導航屬性
3     /// </summary>
4     public class NavigationAttribute : Attribute
5     {
6 
7     }
複製代碼

而對於要進行批量更新的實體,我們需要爲導航屬性添加這個特性

複製代碼
1    public class User
2     {
3         public int UserID { get; set; }
4         [Navigation]
5         public User_Extension User_Extension { get; set; }
6     }
複製代碼

而對於我們構建批量Update語句,請看代碼,它需要對導航屬性進行過濾

複製代碼
 1         /// <summary>
 2         /// 構建Update語句串
 3         /// </summary>
 4         /// <typeparam name="TEntity"></typeparam>
 5         /// <param name="entity"></param>
 6         /// <returns></returns>
 7         private Tuple<string, object[]> CreateUpdateSQL<TEntity>(TEntity entity) where TEntity : class
 8         {
 9             if (entity == null)
10                 throw new ArgumentException("The database entity can not be null.");
11             List<string> pkList = GetPrimaryKey<TEntity>().Select(i => i.Name).ToList();
12 
13             Type entityType = entity.GetType();
14             var table = entityType.GetProperties().Where(i =>
15                 !pkList.Contains(i.Name)
16                 && i.GetValue(entity, null) != null
17                 && i.PropertyType != typeof(EntityState)
18                 && !(i.GetCustomAttributes(false).Length > 0
19                 && i.GetCustomAttributes(false).Where(j => j.GetType() == typeof(NavigationAttribute)) != null)
20                 && (i.PropertyType.IsValueType || i.PropertyType == typeof(string)) //過濾導航屬性
21                  ).ToArray();
22 
23             //過濾主鍵,航行屬性,狀態屬性等
24             if (pkList == null || pkList.Count == 0)
25                 throw new ArgumentException("The Table entity have not a primary key.");
26             List<object> arguments = new List<object>();
27             StringBuilder builder = new StringBuilder();
28 
29             foreach (var change in table)
30             {
31                 if (pkList.Contains(change.Name))
32                     continue;
33                 if (arguments.Count != 0)
34                     builder.Append(", ");
35                 builder.Append(change.Name + " = {" + arguments.Count + "}");
36                 if (change.PropertyType == typeof(string) || change.PropertyType == typeof(DateTime))
37                     arguments.Add("'" + change.GetValue(entity, null).ToString().Replace("'", "char(39)") + "'");
38                 else
39                     arguments.Add(change.GetValue(entity, null));
40             }
41 
42             if (builder.Length == 0)
43                 throw new Exception("沒有任何屬性進行更新");
44 
45             builder.Insert(0, " UPDATE " + string.Format("[{0}]", entityType.Name) + " SET ");
46 
47             builder.Append(" WHERE ");
48             bool firstPrimaryKey = true;
49 
50             foreach (var primaryField in pkList)
51             {
52                 if (firstPrimaryKey)
53                     firstPrimaryKey = false;
54                 else
55                     builder.Append(" AND ");
56 
57                 object val = entityType.GetProperty(primaryField).GetValue(entity, null);
58                 builder.Append(GetEqualStatment(primaryField, arguments.Count));
59                 arguments.Add(val);
60             }
61             return new Tuple<string, object[]>(builder.ToString(), arguments.ToArray());
62 
63         }
複製代碼

而對子類公開的Update方法,我們進行了一個封裝,它通過操作枚舉來確實你是要insert,update還是delete,看代碼

複製代碼
 1         /// <summary>
 2         /// 執行SQL,根據SQL操作的類型
 3         /// </summary>
 4         /// <typeparam name="TEntity"></typeparam>
 5         /// <param name="list"></param>
 6         /// <param name="sqlType"></param>
 7         /// <returns></returns>
 8         protected string DoSQL<TEntity>(IEnumerable<TEntity> list, SQLType sqlType) where TEntity : class
 9         {
10             StringBuilder sqlstr = new StringBuilder();
11             switch (sqlType)
12             {
13                 case SQLType.Insert:
14                     list.ToList().ForEach(i =>
15                     {
16                         Tuple<string, object[]> sql = CreateInsertSQL(i);
17                         sqlstr.AppendFormat(sql.Item1, sql.Item2);
18                     });
19                     break;
20                 case SQLType.Update:
21                     list.ToList().ForEach(i =>
22                     {
23                         Tuple<string, object[]> sql = CreateUpdateSQL(i);
24                         sqlstr.AppendFormat(sql.Item1, sql.Item2);
25                     });
26                     break;
27                 case SQLType.Delete:
28                     list.ToList().ForEach(i =>
29                     {
30                         Tuple<string, object[]> sql = CreateDeleteSQL(i);
31                         sqlstr.AppendFormat(sql.Item1, sql.Item2);
32                     });
33                     break;
34                 default:
35                     throw new ArgumentException("請輸入正確的參數");
36             }
37             return sqlstr.ToString();
38         }
複製代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章