Case_accounting/CaseAccounting/CaseAccountingDataBaseImplement/Implements/UserStorage.cs

110 lines
3.3 KiB
C#
Raw Normal View History

2023-04-08 15:14:22 +04:00
using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.SearchModels;
using CaseAccountingContracts.StoragesContracts;
using CaseAccountingContracts.ViewModels;
using CaseAccountingDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseAccountingDataBaseImplement.Implements
{
public class UserStorage : IUserStorage
{
public UserViewModel? Delete(UserBindingModel model)
{
using var context = new CaseAccountingDatabase();
var element = context.Users
.Include(x => x.Role)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element == null)
{
return null;
}
context.Users.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
public UserViewModel? GetElement(UserSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new CaseAccountingDatabase();
return context.Users
.Include(x => x.Role)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<UserViewModel> GetFilteredList(UserSearchModel model)
{
using var context = new CaseAccountingDatabase();
if (model.Id.HasValue)
{
return context.Users
.Include(x => x.Role)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return new();
}
}
public List<UserViewModel> GetFullList()
{
using var context = new CaseAccountingDatabase();
return context.Users
.Include(x => x.Role)
.Select(x => x.GetViewModel)
.ToList();
}
public UserViewModel? Insert(UserBindingModel model)
{
var newUser = User.Create(model);
if (newUser == null)
{
return null;
}
using var context = new CaseAccountingDatabase();
context.Users.Add(newUser);
context.SaveChanges();
return context.Users
.Include(x => x.Role)
.FirstOrDefault(x => x.Id == newUser.Id)
?.GetViewModel;
}
public UserViewModel? Update(UserBindingModel model)
{
using var context = new CaseAccountingDatabase();
var user = context.Users
.Include(x => x.Role)
.FirstOrDefault(x => x.Id == model.Id);
if (user == null)
{
return null;
}
user.Update(model);
context.SaveChanges();
return context.Users
.Include(x => x.Role)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
}
}