#region 同步單位void SyncUnit() { ProgressContent = "正在同步單位..."; var query = Context.GetUnitsQuery().Where(p => p.ShopUniqueId == App.CurrentShop.UniqueId); Context.Load(query, LoadUnitCallback, null);}void LoadUnitCallback(LoadOperation<RP_Unit> loadOp) { //服務端資料 IEnumerable<RP_Unit> serverUnits = Context.RP_Units; //用戶端資料 IEnumerable<RP_Unit> clientUnits; //擷取資料 using (var helper = new LocalDb.UnitHelper()) { clientUnits = helper.GetList(); } //擷取交集用來同步已存在且需要更新的實體 var intersectUnits = serverUnits.Intersect(clientUnits, new UnitEntityCompare()); //遍曆交集集合 foreach (var item in intersectUnits) { // 根據交集的項目分別擷取服務端及用戶端需要更新的資料 var serverUnitToUpdate = serverUnits.First(p => p.UniqueId == item.UniqueId); var clientUnitToUpdate = clientUnits.First(p => p.UniqueId == item.UniqueId); // 根據更新時間進行比較,如果相同則忽略操作 if (clientUnitToUpdate.UpdateDate != serverUnitToUpdate.UpdateDate) { //如果服務端較新,則更新用戶端 if (clientUnitToUpdate.UpdateDate < serverUnitToUpdate.UpdateDate) { using (var helper = new LocalDb.UnitHelper()) { helper.UpdateUnit(serverUnitToUpdate); } } //否則更新服務端 else { serverUnitToUpdate.UpdateDate = clientUnitToUpdate.UpdateDate; serverUnitToUpdate.NameCN = clientUnitToUpdate.NameCN; serverUnitToUpdate.NameEN = clientUnitToUpdate.NameEN; } } } //擷取服務端與用戶端的差集用來同步服務端或用戶端不存在的實體 var exceptServer = serverUnits.Except(clientUnits, new UnitEntityCompare()); //遍曆差集集合 //由於要修改集合,所以不使用foreach for (int i = 0; i < exceptServer.Count(); i++) { var item = exceptServer.ElementAt(i); //如果本地最後更新時間在資料的更新時間之前,則向用戶端添加該資料 if (!clientShopInfo.LastUpdateDate.HasValue || clientShopInfo.LastUpdateDate < serverShopInfo.LastUpdateDate) { using (var helper = new LocalDb.UnitHelper()) { helper.AddUnit(item); } } //否則說明資料已從本地庫刪除,同時從服務端資料庫刪除 else { Context.RP_Units.Remove(item); } } //擷取服務端與用戶端的差集用來同步服務端或用戶端不存在的實體 var exceptClient = clientUnits.Except(serverUnits, new UnitEntityCompare()); //遍曆差集集合 //由於要修改集合,所以不使用foreach foreach (var item in exceptClient) { //如果本地最後更新時間在資料的更新時間之前,則從用戶端移除該資料 if (clientShopInfo.LastUpdateDate < serverShopInfo.LastUpdateDate) { using (var helper = new LocalDb.UnitHelper()) { helper.DeleteUnit(item); } } //否則說明將用戶端資料添加到服務端 else { Context.RP_Units.Add(item); } } SyncOperations.Remove("Unit");}#endregion