CourseWork_Bank/Bank/BankDatabaseImplement/Implements/CurrencyStorage.cs

101 lines
3.2 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 CurrencyStorage : ICurrencyStorage
{
public CurrencyViewModel? Delete(CurrencyBindingModel model)
{
using var context = new BankDatabase();
var element = context.Currencies.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Currencies.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public CurrencyViewModel? GetElement(CurrencySearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new BankDatabase();
return context.Currencies.Include(x => x.BankOperator)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public List<CurrencyViewModel> GetFilteredList(CurrencySearchModel model)
{
if (!model.Id.HasValue && !model.BankOperatorId.HasValue)
{
return new();
}
if (model.BankOperatorId.HasValue)
{
using var context = new BankDatabase();
return context.Currencies.Include(x => x.BankOperator)
.Where(x => x.BankOperatorId == model.BankOperatorId)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
using var context = new BankDatabase();
return context.Currencies.Include(x => x.BankOperator)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
}
public List<CurrencyViewModel> GetFullList()
{
using var context = new BankDatabase();
return context.Currencies.Include(x => x.BankOperator)
.Select(x => x.GetViewModel)
.ToList();
}
public CurrencyViewModel? Insert(CurrencyBindingModel model)
{
using var context = new BankDatabase();
var newCurrency = Currency.Create(context, model);
if (newCurrency == null)
{
return null;
}
context.Currencies.Add(newCurrency);
context.SaveChanges();
return newCurrency.GetViewModel;
}
public CurrencyViewModel? Update(CurrencyBindingModel model)
{
using var context = new BankDatabase();
var currency = context.Currencies.FirstOrDefault(x => x.Id == model.Id);
if (currency == null)
{
return null;
}
currency.Update(model);
context.SaveChanges();
return currency.GetViewModel;
}
}
}