103 lines
3.0 KiB
C#
103 lines
3.0 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using UniversityContracts.BindingModels;
|
|
using UniversityContracts.SearchModels;
|
|
using UniversityContracts.StoragesContracts;
|
|
using UniversityContracts.ViewModels;
|
|
using UniversityDataBaseImplemet.Models;
|
|
|
|
namespace UniversityDataBaseImplemet.Implements
|
|
{
|
|
public class UserStorage : IUserStorage
|
|
{
|
|
public UserViewModel? Delete(UserBindingModel model)
|
|
{
|
|
using var context = new Database();
|
|
var user = context.User
|
|
.FirstOrDefault(record => record.Id.Equals(model.Id));
|
|
if (user == null)
|
|
{
|
|
return null;
|
|
}
|
|
context.User.Remove(user);
|
|
context.SaveChanges();
|
|
return user.GetViewModel;
|
|
}
|
|
|
|
public UserViewModel? GetElement(UserSearchModel model)
|
|
{
|
|
using var context = new Database();
|
|
if (model.Id.HasValue)
|
|
{
|
|
return context.User
|
|
.FirstOrDefault(x => (x.Id == model.Id))
|
|
?.GetViewModel;
|
|
}
|
|
else if (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && model.Role.HasValue)
|
|
{
|
|
return context.User
|
|
.FirstOrDefault(x => (x.Login == model.Login && x.Password == model.Password && x.Role == model.Role))
|
|
?.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public List<UserViewModel> GetFilteredList(UserSearchModel model)
|
|
{
|
|
using var context = new Database();
|
|
if (model.Id.HasValue)
|
|
{
|
|
return context.User
|
|
.Where(record => record.Id.Equals(model.Id))
|
|
.Select(record => record.GetViewModel)
|
|
.ToList();
|
|
}
|
|
else return new();
|
|
}
|
|
|
|
public List<UserViewModel> GetFullList()
|
|
{
|
|
using var context = new Database();
|
|
return context.User
|
|
.Select(record => record.GetViewModel)
|
|
.ToList();
|
|
}
|
|
|
|
public UserViewModel? Insert(UserBindingModel model)
|
|
{
|
|
var newUser = User.Create(model);
|
|
if (newUser == null)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new Database();
|
|
context.User.Add(newUser);
|
|
context.SaveChanges();
|
|
return newUser.GetViewModel;
|
|
}
|
|
|
|
public UserViewModel? Update(UserBindingModel model)
|
|
{
|
|
using var context = new Database();
|
|
using var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
var user = context.User
|
|
.FirstOrDefault(record => record.Id.Equals(model.Id));
|
|
if (user == null)
|
|
{
|
|
return null;
|
|
}
|
|
user.Update(model);
|
|
context.SaveChanges();
|
|
transaction.Commit();
|
|
return user.GetViewModel;
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|