1.在數據庫中以json字符串格式保存,如:[{"name":"張三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]數據庫
2.添加新內容後合併不相同的數據。若是name相同,以最新的數據替換原來的數據。json
如:數據庫中原保存的數據是[{"name":"張三","time":"8.592","area":"27.27033","conc":"4.12136"},{"name":"李四","time":"9.100","area":"56.21229","conc":"4.57692"}]ide
新加的數據爲[{"name":"張三","time":"12","area":"27.70533","conc":"4.12136"},{"name":"王五","time":"4","area":"77","conc":"8.788"}]spa
則替換後的數據爲[{"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"}]code
代碼以下:blog
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 }
tblLims_Ana_LE_Import_Common 爲數據庫中存數據的表ip
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 }