private static void ChangeOrDeleteExpediture() { Console.WriteLine("Выполняется корректировка трат.\nНа данный момент зарегистрированы следующие пользователи: "); Person person = ChoicePerson(); if (person != null) { Console.WriteLine($"Выбран пользователь: {person.FirstName} {person.LastName}" + $"У данного пользователя есть следующие траты:"); Expenditure expediture = ChoiceExpenditure(person); if (expediture != null) { bool flag = false; do { Console.WriteLine(@"Выберете следующее действие: 1.Корректировать трату 2.Удалить трату 3.Назад"); switch (Console.ReadLine()) { case "1": ChangeExpenditure(expediture); // Корректировать трату break; case "2": AppFunctioality.RemoveExpenditure(expediture); // Удалить трату break; case "3": break; default: flag = true; Console.WriteLine("Введенно некорректное значение"); break; } } while (flag); } else { Console.WriteLine("Данной тараты у данного пользователя не обнаружено."); } } else { Console.WriteLine("Пользователя с таким Id не обнаруженно"); } }
// Удаляем трату internal static void RemoveExpenditure(Expenditure expenditure) { try { using (ApplicationContext db = new ApplicationContext(Configuration.Options)) { db.Expenses.Remove(expenditure); db.SaveChanges(); } Console.WriteLine($"Трата {expenditure.ExpenditureId} {expenditure.Date} пользователя {expenditure.Person.FirstName} {expenditure.Person.LastName} удалена из БД!"); } catch (InvalidOperationException ex) { Console.WriteLine($"#ERROR: {ex.Message}."); } catch (Exception ex) { Console.WriteLine($"Непредевиденная ошибка: {ex.GetType()}"); } }
// Поиск трат по дате. Находится подходящая трата и возвращает его ID internal static int FindExpenditure(DateTime date, decimal sum) { Expenditure expenditure = null; try { using (ApplicationContext db = new ApplicationContext(Configuration.Options)) { expenditure = db.Expenses.FirstOrDefault(expend => expend.Date == date && expend.TotalSum == sum); } } catch (InvalidOperationException ex) { Console.WriteLine($"#ERROR: {ex.Message}."); } catch (Exception ex) { Console.WriteLine($"Непредевиденная ошибка: {ex.GetType()}"); } return(expenditure.ExpenditureId); }
// Корректировка траты private static void ChangeExpenditure(Expenditure expenditure) { Console.WriteLine($"\n\nТрата пользователя {expenditure.Person.FirstName} {expenditure.Person.LastName} имеет следующие параметры:\n" + $"Sum - {expenditure.TotalSum};\nDate - {expenditure.Date};\nCategory - {expenditure.Category};\n" + $"и содержит следующие продукты:"); AppFunctioality.ToPrintProduct(expenditure); decimal newSum; Console.WriteLine("Введите новое значение Sum:"); while (!Decimal.TryParse(Console.ReadLine(), out newSum)) { ; } char newCat; Console.WriteLine("Введите новое значение категории товара:"); while (!Char.TryParse(Console.ReadLine(), out newCat)) { Console.WriteLine("Выберете новое значение Date:"); } DateTime newDate = ImputDateFull(); if (newSum != expenditure.TotalSum) { AppFunctioality.RemoveExpenditure(expenditure); AppFunctioality.AddExpenditure(expenditure.Person.PersonId, newCat, newSum, newDate); Console.WriteLine("Введите обновленные данные о товарах:"); AddProducts(newDate, newSum); } else { AppFunctioality.ChangeExpenditure(expenditure, newCat, newSum, newDate); } }
// Изменяем трату internal static void ChangeExpenditure(Expenditure expenditure, char category, decimal sum, DateTime date) { try { using (ApplicationContext db = new ApplicationContext(Configuration.Options)) { expenditure.Category = category; expenditure.TotalSum = sum; expenditure.Date = date; db.Expenses.Update(expenditure); db.SaveChanges(); } Console.WriteLine($"Трата пользователя {expenditure.Person.FirstName} {expenditure.Person.LastName} изменена."); } catch (InvalidOperationException ex) { Console.WriteLine($"#ERROR: {ex.Message}."); } catch (Exception ex) { Console.WriteLine($"Непредевиденная ошибка: {ex.GetType()}"); } }
// Поиск траты по ее Id. internal static Expenditure FindExpenditure(Person person, int idExpenditure) { Expenditure expenditure = null; try { using (ApplicationContext db = new ApplicationContext(Configuration.Options)) { expenditure = db.Expenses.Include(ex => ex.Person). FirstOrDefault(exp => exp.ExpenditureId == idExpenditure && exp.Person.PersonId == person.PersonId); } } catch (InvalidOperationException ex) { Console.WriteLine($"#ERROR: {ex.Message}."); } catch (Exception ex) { Console.WriteLine($"Непредевиденная ошибка: {ex.GetType()}"); } return(expenditure); }
//----------------------------------------Work with Product--------------------------------------------------------------- // Добавление нового продукта к Expenditure internal static void AddProduct(int expenditureId, string productName, decimal cost, int count) { try { using (ApplicationContext db = new ApplicationContext(Configuration.Options)) { Expenditure expenditure = db.Expenses.First(exp => exp.ExpenditureId == expenditureId); Product product = new Product { ProductName = productName, ProductCost = cost, ProductCount = count, Expenses = expenditure }; db.Products.Add(product); db.SaveChanges(); Console.WriteLine($"Добавленна новый продукт: {productName} - стоимостью {cost} в коллиечтве {count} к тратам {expenditure.Date} - {expenditure.TotalSum}"); } } catch (InvalidOperationException ex) { Console.WriteLine($"#ERROR: {ex.Message}."); } catch (Exception ex) { Console.WriteLine($"Непредевиденная ошибка: {ex.GetType()}"); } }
//----------------------------------------Work with Expenditure------------------------------------------------------------ // Добавления новой траты к Person internal static void AddExpenditure(int personId, char category, decimal sum, DateTime time) { try { using (ApplicationContext db = new ApplicationContext(Configuration.Options)) { Person person = db.Persons.First(per => per.PersonId == personId); Expenditure expenditure = new Expenditure { Category = category, TotalSum = sum, Date = time, Person = person }; db.Expenses.Add(expenditure); db.SaveChanges(); Console.WriteLine($"Добавленна новая трата: {time} - {sum} к {person.FirstName} {person.LastName}"); } } catch (InvalidOperationException ex) { Console.WriteLine($"#ERROR: {ex.Message}."); } catch (Exception ex) { Console.WriteLine($"Непредевиденная ошибка: {ex.GetType()}"); } }