PIAPS_CW/DatabaseImplement/Implements/UserStorage.cs

109 lines
2.5 KiB
C#
Raw Normal View History

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
2024-06-04 22:52:59 +04:00
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
2024-06-06 17:52:09 +04:00
using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class UserStorage : IUserStorage
{
public UserBindingModel? Delete(UserSearchModel model)
{
2024-06-04 23:43:52 +04:00
if (model.Id is null && model.Email is null)
{
return null;
}
var context = new Database();
2024-06-06 17:52:09 +04:00
var user = context.Users.FirstOrDefault(u =>
(model.Id.HasValue && u.Id == model.Id)
|| (!string.IsNullOrEmpty(u.Email) && u.Email.Contains(model.Email)));
if (user is null)
{
return null;
}
context.Remove(user);
context.SaveChanges();
return user.GetBindingModel();
}
public UserBindingModel? GetElement(UserSearchModel model)
{
2024-06-04 23:43:52 +04:00
if (model.Id is null && model.Email is null)
{
return null;
}
var context = new Database();
return context.Users
2024-06-04 22:52:59 +04:00
.Include(u => u.Role)
2024-06-06 17:52:09 +04:00
.FirstOrDefault(u =>
(model.Id.HasValue && u.Id == model.Id)
|| (!string.IsNullOrEmpty(u.Email) && u.Email.Contains(model.Email)))
?.GetBindingModel();
}
public IEnumerable<UserBindingModel> GetList(UserSearchModel? model)
{
var context = new Database();
if (model is null)
{
2024-06-04 22:52:59 +04:00
return context.Users
.Include(u => u.Role)
.Select(r => r.GetBindingModel());
}
if (model.Id is null && model.Email is null)
{
return [];
}
return context.Users
2024-06-06 17:52:09 +04:00
.Where(u =>
(model.Id.HasValue && u.Id == model.Id)
|| (!string.IsNullOrEmpty(u.Email) && u.Email.Contains(model.Email)))
2024-06-04 22:52:59 +04:00
.Include(u => u.Role)
.Select(r => r.GetBindingModel());
}
public UserBindingModel? Insert(UserBindingModel model)
{
var context = new Database();
2024-06-06 17:52:09 +04:00
var role = context.Roles.FirstOrDefault(r => r.Id == model.Role.Id);
if (role is null)
{
return null;
}
var newUser = Models.User.ToUserFromBinding(model, role);
context.Users.Add(newUser);
context.SaveChanges();
return newUser.GetBindingModel();
}
public UserBindingModel? Update(UserBindingModel model)
{
var context = new Database();
2024-06-04 22:52:59 +04:00
var user = context.Users
.FirstOrDefault(u => u.Id == model.Id);
2024-06-06 17:52:09 +04:00
var role = context.Roles.FirstOrDefault(r => r.Id == model.Role.Id);
2024-06-06 17:52:09 +04:00
if (user is null || role is null)
{
return null;
}
2024-06-06 17:52:09 +04:00
user.Update(model, role);
context.SaveChanges();
return user.GetBindingModel();
}
}
}