using Microsoft.EntityFrameworkCore; using SchoolContracts.BindingModels; using SchoolContracts.SearchModel; using SchoolContracts.StoragesContracts; using SchoolContracts.ViewModels; using SchoolDatabaseImplement; using SchoolDatabaseImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolDatabaseImplements.Implements { internal class ExpenseStorage : IExpenseStorage { public ExpenseViewModel? Delete(ExpenseBindingModel model) { using var context = new SchoolDatabase(); var element = context.Expenses.FirstOrDefault(x => x.Id == model.Id); if (element != null) { context.Expenses.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public ExpenseViewModel GetElement(ExpenseSearchModel model) { using var context = new SchoolDatabase(); if (model.Id.HasValue)//сначала ищем по Id { return context.Expenses .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } if (!string.IsNullOrEmpty(model.ExpenseName))//затем по названию { return context.Expenses .FirstOrDefault(x => x.ExpenseName == model.ExpenseName)?.GetViewModel; } return null; } public List GetFilteredList(ExpenseSearchModel model) { using var context = new SchoolDatabase(); return context.Expenses .Where (x => x.Id == model.Id) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new SchoolDatabase(); return context.Expenses .Select(x => x.GetViewModel) .ToList(); } public ExpenseViewModel? Insert(ExpenseBindingModel model) { using var context = new SchoolDatabase(); var newExpense = Expense.Create(context, model); if (newExpense == null) { return null; } context.Expenses.Add(newExpense); context.SaveChanges(); return newExpense.GetViewModel; } public ExpenseViewModel? Update(ExpenseBindingModel model) { using var context = new SchoolDatabase(); var expense = context.Expenses.FirstOrDefault(x => x.Id == model.Id); if (expense == null) { return null; } expense.Update(model); context.SaveChanges(); return expense.GetViewModel; } } }