2024-11-28 01:31:31 +04:00

97 lines
2.2 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class AccountStorage : IAccountStorage
{
public AccountViewModel? Delete(AccountBindingModel model)
{
using var context = new AccountsDatabase();
var element = context.Accounts
.Include(x => x.ResidenceCity)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Accounts.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public AccountViewModel? GetElement(AccountSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new AccountsDatabase();
return context.Accounts
.Include(x => x.ResidenceCity)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public List<AccountViewModel> GetFilteredList(AccountSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new AccountsDatabase();
return context.Accounts
.Include(x => x.ResidenceCity)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public List<AccountViewModel> GetFullList()
{
using var context = new AccountsDatabase();
return context.Accounts
.Include(x => x.ResidenceCity)
.Select(x => x.GetViewModel)
.ToList();
}
public AccountViewModel? Insert(AccountBindingModel model)
{
using var context = new AccountsDatabase();
var newAccount = Accounts.Create(context, model);
if (newAccount == null)
{
return null;
}
context.Accounts.Add(newAccount);
context.SaveChanges();
return newAccount.GetViewModel;
}
public AccountViewModel? Update(AccountBindingModel model)
{
using var context = new AccountsDatabase();
var Account = context.Accounts.FirstOrDefault(x => x.Id == model.Id);
if (Account == null)
{
return null;
}
Account.Update(model, context);
context.SaveChanges();
return Account.GetViewModel;
}
}
}