1.在数据库中以json字符串格式保存,如:[{"name":"张三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]
2.添加新内容后合并不相同的数据。如果name相同,以最新的数据替换原来的数据。
如:数据库中原保存的数据是[{"name":"张三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]
新加的数据为[{"name":"张三","time":"12","area":"27.70533","conc":"4.12136"},{"name":"王五","time":"4","area":"77","conc":"8.788"}]
则替换后的数据为[{"name":"张三","time":"12","area":"27.70533","conc":"4.12136"},{"name":"王五","time":"4","area":"77","conc":"8.788"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]
代码如下:
class="code_img_closed" src="/Upload/Images/2013101415/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('f3a4093a-bc18-4e78-b4e1-aa184f391488',event)" src="/Upload/Images/2013101415/2B1B950FA3DF188F.gif" alt="" />
1 public void InsertOrUpdateOnlyItem(List<tblLims_Ana_LE_Import_Common> listLe) 2 { 3 var listLeInsert = new List<tblLims_Ana_LE_Import_Common>(); 4 var listLeUpdate = new List<tblLims_Ana_LE_Import_Common>(); 5 foreach (var le in listLe) 6 { 7 tblLims_Ana_LE_Import_Common model = le; 8 var own = CurrentRepository.Find(a => a.fldTaskID == model.fldTaskID 9 && a.fldBizCatID == model.fldBizCatID 10 && a.fldItemCode == model.fldItemCode 11 && a.fldNumber == model.fldNumber 12 && a.fldSampleCode == model.fldSampleCode); 13 if (own != null) 14 { 15 var ser = new JavaScriptSerializer(); 16 17 var listown = ser.Deserialize<List<Dictionary<string, string>>>(own.fldImportData); //原数据 18 var listmodel = ser.Deserialize<List<Dictionary<string, string>>>(model.fldImportData); //新数据 19 IEqualityComparer<Dictionary<string, string>> ec = new EntityComparer(); //自定义的比较类 20 own.fldImportData = ser.Serialize(listmodel.Union(listown, ec)); //合并数据 21 22 23 listLeUpdate.Add(own); 24 } 25 else 26 { 27 listLeInsert.Add(model); 28 } 29 } 30 CurrentRepository.UpdateAll(listLeUpdate); 31 CurrentRepository.InsertAll(listLeInsert); 32 CurrentRepository.Save(); 33 }View Code
tblLims_Ana_LE_Import_Common 为数据库中存数据的表
Union() 方法中用到的自定义比较类:
1 /// <summary> 2 /// 自定义比较类 3 /// </summary> 4 public class EntityComparer : IEqualityComparer<Dictionary<string, string>> 5 { 6 public bool Equals(Dictionary<string, string> x, Dictionary<string, string> y) 7 { 8 if (ReferenceEquals(x, y)) return true; 9 10 if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) 11 return false; 12 13 return x["name"] == y["name"]; //如果名称相同就不追加 14 } 15 16 public int GetHashCode(Dictionary<string, string> obj) 17 { 18 if (ReferenceEquals(obj, null)) return 0; 19 int hashName = obj["name"] == null ? 0 : obj["name"].GetHashCode(); 20 int hashCode = obj["name"] == null ? 0 : obj["name"].GetHashCode(); 21 return hashName ^ hashCode; 22 } 23 }View Code