public BudgetList SaveBudgets(BudgetList budgets) { try { bool updateFound = false; using (EntityContext context = new EntityContext()) { foreach (var item in budgets) { if (item.BudgetId > 0) //Update { var original = context.Budget.Where(t => t.BudgetId == item.BudgetId && t.ModifiedDate < item.ModifiedDate && !t.IsDeleted).FirstOrDefault(); //update database only if the transaction in DB is older if (original != null) { item.HasChanges = false; original.CreatedUser = context.User.Where(k => !k.IsDeleted).Single(p => p.UserId == item.CreatedUser.UserId); original.ModifiedUser = context.User.Where(k => !k.IsDeleted).Single(p => p.UserId == item.ModifiedUser.UserId); item.FromDate = new DateTime(item.FromDate.Year, item.FromDate.Month, item.FromDate.Day, 0, 0, 0); item.ToDate = new DateTime(item.ToDate.Year, item.ToDate.Month, item.ToDate.Day, 0, 0, 0); context.Entry(original).CurrentValues.SetValues(item); updateFound = true; } } else //Insert { item.CreatedUser = context.User.Where(k => !k.IsDeleted).Single(p => p.UserId == item.CreatedUser.UserId); item.ModifiedUser = context.User.Where(k => !k.IsDeleted).Single(p => p.UserId == item.ModifiedUser.UserId); item.FromDate = new DateTime(item.FromDate.Year, item.FromDate.Month, item.FromDate.Day, 0, 0, 0); item.ToDate = new DateTime(item.ToDate.Year, item.ToDate.Month, item.ToDate.Day, 0, 0, 0); context.Budget.Add(item); updateFound = true; } } if (updateFound) context.SaveChanges(); } GetTransactionsForBudgets(budgets); budgets.PrepareForServiceSerialization(); return budgets; } catch (DbEntityValidationException e) { StringBuilder s = new StringBuilder(); foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); s.Append(string.Format("{0} - {1}", ve.PropertyName, ve.ErrorMessage)); } } throw new DbEntityValidationException(s.ToString()); } catch (Exception) { throw; } }
public BudgetList GetAllBudgets(int userId) { try { BudgetList budgetList = new BudgetList(); using (EntityContext context = new EntityContext()) { var query = (from i in context.Budget .Include(i => i.CreatedUser) .Include(i => i.ModifiedUser) where !i.IsDeleted && i.ModifiedUser.UserId == userId select i).ToList(); //investigate if there is a better way to convert the generic list to ObservableCollection foreach (var item in query) budgetList.Add(item); GetTransactionsForBudgets(budgetList); budgetList.PrepareForServiceSerialization(); return budgetList; } } catch (Exception) { throw; } }