CourseWork_Bank/Bank/BankDatabaseImplement/Implements/DealStorage.cs

96 lines
3.1 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 DealStorage : IDealStorage
{
public List<DealViewModel> GetFullList()
{
using var context = new BankDatabase();
return context.Deals.Include(x => x.Operator).Include(x => x.CreditProgram)
.Select(x => x.GetViewModel)
.ToList();
}
public List<DealViewModel> GetFilteredList(DealSearchModel model)
{
if (!model.Id.HasValue && !model.OperatorId.HasValue)
{
return new();
}
if (model.OperatorId.HasValue)
{
using var context = new BankDatabase();
return context.Deals.Include(x => x.Operator).Include(x => x.CreditProgram)
.Where(x => x.OperatorId == model.OperatorId)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
using var context = new BankDatabase();
return context.Deals.Include(x => x.Operator).Include(x => x.CreditProgram)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
}
public DealViewModel? GetElement(DealSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new BankDatabase();
return context.Deals.Include(x => x.Operator).Include(x => x.CreditProgram)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public DealViewModel? Insert(DealBindingModel model)
{
using var context = new BankDatabase();
var newDeal = Deal.Create(context, model);
if (newDeal == null)
{
return null;
}
context.Deals.Add(newDeal);
context.SaveChanges();
return newDeal.GetViewModel;
}
public DealViewModel? Update(DealBindingModel model)
{
using var context = new BankDatabase();
var deal = context.Deals.FirstOrDefault(x => x.Id == model.Id);
if (deal == null)
{
return null;
}
deal.Update(model);
context.SaveChanges();
return deal.GetViewModel;
}
public DealViewModel? Delete(DealBindingModel model)
{
using var context = new BankDatabase();
var element = context.Deals.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Deals.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}