CourseWork_Bank/Bank/BankDatabaseImplement/Implements/OperatorStorage.cs

85 lines
2.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 OperatorStorage : IOperatorStorage
{
public List<OperatorViewModel> GetFullList()
{
using var context = new BankDatabase();
return context.Operators
.Select(x => x.GetViewModel)
.ToList();
}
public List<OperatorViewModel> GetFilteredList(OperatorSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new BankDatabase();
return context.Operators
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public OperatorViewModel? GetElement(OperatorSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new BankDatabase();
return context.Operators
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public OperatorViewModel? Insert(OperatorBindingModel model)
{
using var context = new BankDatabase();
var newOperator = Operator.Create(model);
if (newOperator == null)
{
return null;
}
context.Operators.Add(newOperator);
context.SaveChanges();
return newOperator.GetViewModel;
}
public OperatorViewModel? Update(OperatorBindingModel model)
{
using var context = new BankDatabase();
var operatorUpd = context.Operators.FirstOrDefault(x => x.Id == model.Id);
if (operatorUpd == null)
{
return null;
}
operatorUpd.Update(model);
context.SaveChanges();
return operatorUpd.GetViewModel;
}
public OperatorViewModel? Delete(OperatorBindingModel model)
{
using var context = new BankDatabase();
var element = context.Operators.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Operators.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}