PIbd-22-Ismailov_SUBD/BlogDataModels/BlogDatabaseImplement/Implements/UserStorage.cs
2023-05-18 21:34:36 +04:00

90 lines
2.8 KiB
C#

using BlogContracts.BindingModel;
using BlogContracts.SearchModels;
using BlogContracts.StorageContracts;
using BlogContracts.ViewModels;
using BlogDatabaseImplement.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlogDatabaseImplement.Implements
{
public class UserStorage : IUserStorage
{
public List<UserViewModel> GetFullList()
{
using var context = new BlogDatabase();
return context.Users
.Select(x => x.GetViewModel)
.ToList();
}
public List<UserViewModel> GetFilteredList(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new BlogDatabase();
return context.Users
.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel)
.ToList();
}
public UserViewModel? GetElement(UserSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new BlogDatabase();
return context.Users
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) ||
(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 BlogDatabase();
context.Users.Add(newUser);
context.SaveChanges();
return newUser.GetViewModel;
}
public UserViewModel? Update(UserBindingModel model)
{
using var context = new BlogDatabase();
var component = context.Users.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public UserViewModel? Delete(UserBindingModel model)
{
using var context = new BlogDatabase();
var element = context.Users.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Users.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}