124 lines
3.6 KiB
C#
Raw Normal View History

using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client;
using BankContracts.StoragesModels.Client;
using BankContracts.ViewModels.Client.ViewModels;
using BankDatabaseImplement.Models.ClientModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankDatabaseImplement.Implements.ClientImplements
{
// Реализация интерфейса хранилища для сущности "Снятие с карты"
public class DebitingStorage : IDebitingStorage
{
public DebitingViewModel? GetElement(DebitingSearchModel model)
{
if (model.CardId < 0 && !model.Id.HasValue)
{
return null;
}
using var context = new BankDatabase();
return context.Debitings
.Include(x => x.Card)
.FirstOrDefault(x => (!(model.CardId < 0) && x.CardId == model.CardId) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<DebitingViewModel> GetFilteredList(DebitingSearchModel model)
{
using var context = new BankDatabase();
var result = context.Debitings.Include(x => x.Card).ToList();
// Для получения всех заявок на стнятие
if (model.CardId.HasValue) result = result.Where(x => x.CardId == model.CardId).ToList();
if (model.ClientId.HasValue)
{
List<int> cards = context.Cards.Where(x => x.ClientId == model.ClientId).Select(x => x.Id).ToList();
result = result.Where(x => cards.Contains(x.CardId)).ToList();
}
return result.Select(x => x.GetViewModel).ToList();
}
public List<DebitingViewModel> GetFullList()
{
using var context = new BankDatabase();
return context.Debitings
.Include(x => x.Card)
.Select(x => x.GetViewModel)
.ToList();
}
public DebitingViewModel? Insert(DebitingBindingModel model)
{
using var context = new BankDatabase();
var newDebiting = Debiting.Create(context, model);
if (newDebiting == null)
{
return null;
}
context.Debitings.Add(newDebiting);
context.SaveChanges();
return newDebiting.GetViewModel;
}
public DebitingViewModel? Update(DebitingBindingModel model)
{
using var context = new BankDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var debiting = context.Debitings.FirstOrDefault(rec => rec.Id == model.Id);
debiting.Update(model);
context.SaveChanges();
transaction.Commit();
return context.Debitings
.Include(x => x.Card)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public DebitingViewModel? Delete(DebitingBindingModel model)
{
using var context = new BankDatabase();
var element = context.Debitings
.Include(x => x.CardId)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Debitings.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}