PIbd-21_Medvedkov_Coursach/ComputerShopDatabaseImplement/Implements/UserStorage.cs

69 lines
1.7 KiB
C#
Raw Permalink Normal View History

2024-05-01 04:42:57 +04:00
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopDatabaseImplement.Implements
{
public class UserStorage : IUserStorage
{
public List<UserViewModel> GetFullList()
{
using var context = new ComputerShopDatabase();
return context.Users.Select(x => x.GetViewModel).ToList();
}
public UserViewModel? GetElement(UserSearchModel model)
{
using var context = new ComputerShopDatabase();
return context.Users.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public UserViewModel? Insert(UserBindingModel model)
{
var newUser = User.Create(model);
if (newUser == null)
{
return null;
}
using var context = new ComputerShopDatabase();
context.Users.Add(newUser);
context.SaveChanges();
return newUser.GetViewModel;
}
public UserViewModel? Update(UserBindingModel model)
{
using var context = new ComputerShopDatabase();
var user = context.Users.FirstOrDefault(x => x.Id == model.Id);
if (user == null)
{
return null;
}
user.Update(model);
context.SaveChanges();
return user.GetViewModel;
}
public UserViewModel? Delete(UserBindingModel model)
{
using var context = new ComputerShopDatabase();
var user = context.Users.FirstOrDefault(rec => rec.Id == model.Id);
if (user != null)
{
context.Users.Remove(user);
context.SaveChanges();
return user.GetViewModel;
}
return null;
}
}
}