CourseWork_Bank/Bank/BankDatabaseImplement/Implements/CreditProgramStorage.cs

106 lines
3.7 KiB
C#

using BankContracts.BindingModels;
using BankContracts.SearchModels;
using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankDatabaseImplement.Implements
{
public class CreditProgramStorage : ICreditProgramStorage
{
public CreditProgramViewModel? Delete(CreditProgramBindingModel model)
{
using var context = new BankDatabase();
var element = context.CreditPrograms.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.CreditPrograms.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public CreditProgramViewModel? GetElement(CreditProgramSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new BankDatabase();
return context.CreditPrograms.Include(x => x.BankOperator)
.Include(x => x.Currencies).ThenInclude(x => x.Currency)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public List<CreditProgramViewModel> GetFilteredList(CreditProgramSearchModel model)
{
if (!model.Id.HasValue && !model.BankOperatorId.HasValue)
{
return new();
}
if (model.BankOperatorId.HasValue)
{
using var context = new BankDatabase();
return context.CreditPrograms.Include(x => x.BankOperator)
.Include(x => x.Currencies).ThenInclude(x => x.Currency)
.Where(x => x.BankOperatorId == model.BankOperatorId)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
using var context = new BankDatabase();
return context.CreditPrograms.Include(x => x.BankOperator)
.Include(x => x.Currencies).ThenInclude(x => x.Currency)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
}
public List<CreditProgramViewModel> GetFullList()
{
using var context = new BankDatabase();
return context.CreditPrograms.Include(x => x.BankOperator)
.Include(x => x.Currencies).ThenInclude(x => x.Currency)
.Select(x => x.GetViewModel)
.ToList();
}
public CreditProgramViewModel? Insert(CreditProgramBindingModel model)
{
using var context = new BankDatabase();
var newCreditProgram = CreditProgram.Create(context, model);
if (newCreditProgram == null)
{
return null;
}
context.CreditPrograms.Add(newCreditProgram);
context.SaveChanges();
return newCreditProgram.GetViewModel;
}
public CreditProgramViewModel? Update(CreditProgramBindingModel model)
{
using var context = new BankDatabase();
var creditProgram = context.CreditPrograms.FirstOrDefault(x => x.Id == model.Id);
if (creditProgram == null)
{
return null;
}
creditProgram.Update(model);
creditProgram.UpdateCurrencies(context, model);
context.SaveChanges();
return creditProgram.GetViewModel;
}
}
}