SUBD-Petrushin-Egor-PIbd-22/TaskTrackerDatabase/Implements/UserStorage.cs
2024-05-13 14:29:34 +04:00

89 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaskTrackerContracts.BindingModels;
using TaskTrackerContracts.SearchModels;
using TaskTrackerContracts.StoragesContracts;
using TaskTrackerContracts.ViewModels;
using TaskTrackerDatabase.Models;
namespace TaskTrackerDatabase.Implements
{
public class UserStorage : IUserStorage
{
public List<UserViewModel> GetFullList()
{
using var context = new TaskTrackerDatabase();
return context.Users
.Select(x => x.GetViewModel)
.ToList();
}
public List<UserViewModel> GetFilteredList(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Email))
{
return new();
}
using var context = new TaskTrackerDatabase();
return context.Users
.Where(x => x.Email.Contains(model.Email))
.Select(x => x.GetViewModel)
.ToList();
}
public UserViewModel? GetElement(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue)
{
return null;
}
using var context = new TaskTrackerDatabase();
return context.Users.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && !string.IsNullOrEmpty(model.Password) && x.Password == model.Password)
|| (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public UserViewModel? Insert(UserBindingModel model)
{
var newUser = User.Create(model);
if (newUser == null)
{
return null;
}
using var context = new TaskTrackerDatabase();
context.Users.Add(newUser);
context.SaveChanges();
return newUser.GetViewModel;
}
public UserViewModel? Update(UserBindingModel model)
{
using var context = new TaskTrackerDatabase();
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 TaskTrackerDatabase();
var element = context.Users.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Users.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}