public int Save(ObservableCollection <ServiceModel> models) { using (DBConnect connect = new DBFactory().GetPostgreSQLDBConnect().BeginTransaction()) { try { int res = 0; var list = connect.FindAll <DBModels.PostgreSQL.Service, int>(m => m.Id); var data = list.Where(w => !models.Select(s => s.Id).Contains(w.Id)); res += connect.Delete(data); foreach (ServiceModel model in models) { DBModels.PostgreSQL.Service service = new DBModels.PostgreSQL.Service(); ModelHelper.CopyModel(service, model); service.GroupCode = model.ServiceGroup.Code; Func <DBModels.PostgreSQL.Service, bool> func = m => { if (m.Id == model.Id) { if (m.Code == model.Code && m.Name == model.Name && m.GroupCode == model.ServiceGroup.Code && m.Price == model.Price) { return(false); } else { return(true); } } return(false); }; if (model.Id < 1) { service.CreateTime = DateTime.Now.ToLongDateString(); res += connect.Add(service); } else if (list.Where(func).Count() > 0) { service.UpdateTime = DateTime.Now.ToLongDateString(); res += connect.Modify(service); } } connect.Commite(); return(res); } catch (Exception ex) { connect.Rollback(); AppLog.Error(typeof(ServiceControl), ex.ToString()); throw new AppException("DBException"); } } }
//没有共通化 public int SaveSalonService(string salonCd, ObservableCollection <ServiceModel> models) { using (var context = new PostgreSQLContext()) { using (var transaction = context.Database.BeginTransaction()) { try { int res = 0; var salonServices = context.SalonServices.Where(s => s.SalonCode == salonCd).Include(s => s.Service).ToList(); var data = salonServices.Where(w => !models.Select(s => s.Code).Contains(w.Service.Code)); context.SalonServices.RemoveRange(data); foreach (ServiceModel model in models) { if (salonServices.Where(w => w.Service.Code == model.Code).Count() < 1) { DBModels.PostgreSQL.SalonService salon = new DBModels.PostgreSQL.SalonService(); DBModels.PostgreSQL.Service service = context.Services.Where(s => s.Code == model.Code).First(); salon.SalonCode = salonCd; salon.ServiceCode = model.Code; salon.Service = service; context.SalonServices.Add(salon); } } res += context.SaveChanges(); transaction.Commit(); return(res); } catch (Exception ex) { transaction.Rollback(); AppLog.Error(typeof(SalonControl), ex.ToString()); throw new AppException("DBException"); } } } }