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

114 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.CircleLesson)
.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.CircleLessonId == model.CircleLessonId)
.OrderBy(x => x.DateOfPayment)
.Include(x => x.CircleLesson);
return list
.Select(x => new PaymentViewModel
{
DateOfPayment = x.DateOfPayment,
Id = x.Id,
PaySum = x.PaySum,
CircleLessonId = x.CircleLessonId
})
.ToList();
}
public PaymentViewModel GetElement(PaymentSearchModel model)
{
if (model == null)
{
return null;
}
using var context = new SchoolDatabase();
{
var payment = context.Payments.Include(x=> x.CircleLesson)
.FirstOrDefault(x => x.CircleLessonId == model.CircleLessonId);
return payment != null ? new PaymentViewModel
{
DateOfPayment = payment.DateOfPayment,
Id = payment.Id,
PaySum = payment.PaySum,
CircleLessonId = payment.CircleLessonId
} :
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.CircleLesson)
.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.CircleLesson)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Payments.Remove(element);
context.SaveChanges();
return element?.GetViewModel;
}
else
{
throw new Exception("Оплата не найдена");
}
}
}
}