EF架(jia)構~性(xing)能高效(xiao)的批量(liang)操作(Insert篇)
無論是(shi)(shi)linq to sql 還是(shi)(shi)entity frameworks,在進行列(lie)表操作(zuo)時都會有一個毛(mao)病,那(nei)就(jiu)是(shi)(shi)它的(de)操作(zuo)只能一個實體(ti)一個實體(ti)的(de)發(fa)到(dao)服務器,這樣,如果(guo)列(lie)表的(de)數(shu)量(liang)很大,如列(lie)表為10萬條數(shu)據,那(nei)么,這種操作(zuo)將是(shi)(shi)非常性能的(de),可能你的(de)DB就(jiu)掛了(le)。
解(jie)決(jue)方案:拼(pin)接(jie)T—SQL串,并使它具有通(tong)用性
好處:與服務(wu)(wu)器建(jian)立一(yi)次連接(jie),給(gei)服務(wu)(wu)器發一(yi)條SQL命令,即可實現
代碼如下:
1 /// <summary> 2 /// 構建Insert語句串 3 /// 主(zhu)鍵為(wei)自增時,如(ru)果主(zhu)鍵值為(wei)0,我們(men)將主(zhu)鍵插入到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();//過(guo)濾主鍵(jian),航(hang)行屬性,狀態(tai)屬性等(deng) 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 }
之(zhi)后(hou)我將(jiang)陸續把(ba)更新操(cao)作(zuo)與(yu)刪(shan)除操(cao)作(zuo)及對增(zeng)刪(shan)改操(cao)作(zuo)進行(xing)封裝,獻給大家,盡請期待。