ISEbd-21_Tukaeva_A_A_School/School/SchoolDatabaseImplements/Implements/PaymentStorage.cs

116 lines
2.8 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore;
using SchoolContracts.BindingModel;
using SchoolContracts.BindingModels;
using SchoolContracts.SearchModel;
using SchoolContracts.StoragesContracts;
using SchoolContracts.ViewModels;
using SchoolDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SchoolDatabaseImplement.Implements
{
public class PaymentStorage : IPaymentStorage
{
public List<PaymentViewModel> GetFullList()
{
using var context = new SchoolDatabase();
return context.Payments
.Include(rec => rec.Lesson)
.Select(x => x.GetViewModel)
.ToList();
}
public List<PaymentViewModel> GetFilteredList(PaymentSearchModel model)
{
if (model == null)
{
return null;
}
using var context = new SchoolDatabase();
var list = context.Payments.Where(x => x.LessonId == model.LessonId)
.OrderBy(x => x.DateOfPayment)
.Include(x => x.Lesson);
return list
.Select(x => new PaymentViewModel
{
DateOfPayment = x.DateOfPayment,
Id = x.Id,
Remains = x.Remains,
Sum = x.Sum,
LessonId = x.LessonId
})
.ToList();
}
public PaymentViewModel GetElement(PaymentSearchModel model)
{
if (model == null)
{
return null;
}
using var context = new SchoolDatabase();
{
var payment = context.Payments.Include(x=> x.Lesson)
.FirstOrDefault(x => x.LessonId == model.LessonId);
return payment != null? new PaymentViewModel
{
DateOfPayment = payment.DateOfPayment,
Id = payment.Id,
Remains = payment.Lesson.LessonPrice,
Sum = payment.Sum,
LessonId = payment.LessonId
} :
null;
}
}
public PaymentViewModel? Insert(PaymentBindingModel model)
{
var context = new SchoolDatabase();
var newPayment = Payment.Create(context, model);
if (newPayment == null)
{
return null;
}
context.Payments.Add(newPayment);
context.SaveChanges();
return newPayment.GetViewModel;
}
public PaymentViewModel? Update(PaymentBindingModel model)
{
var context = new SchoolDatabase();
var element = context.Payments.
Include(x => x.Lesson)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element == null)
{
throw new Exception("Оплата не найдена");
}
element.Update(model);
context.SaveChanges();
return element.GetViewModel;
}
public PaymentViewModel? Delete(PaymentBindingModel model)
{
var context = new SchoolDatabase();
var element = context.Payments
.Include(x => x.Lesson)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Payments.Remove(element);
context.SaveChanges();
return element?.GetViewModel;
}
else
{
throw new Exception("Оплата не найдена");
}
}
}
}