PIAPS_CW/DatabaseImplement/Implements/UserStorage.cs

93 lines
1.9 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StorageContracts;
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)
{
if (model is null || (model.Id is null && model.Email is null))
{
return null;
}
var context = new Database();
var user = context.Users.FirstOrDefault(u => u.Equals(model));
if (user is null)
{
return null;
}
context.Remove(user);
context.SaveChanges();
return user.GetBindingModel();
}
public UserBindingModel? GetElement(UserSearchModel model)
{
if (model is null || (model.Id is null && model.Email is null))
{
return null;
}
var context = new Database();
return context.Users
.FirstOrDefault(u => u.Equals(model))
?.GetBindingModel();
}
public IEnumerable<UserBindingModel> GetList(UserSearchModel? model)
{
var context = new Database();
if (model is null)
{
return context.Users.Select(r => r.GetBindingModel());
}
if (model.Id is null && model.Email is null)
{
return [];
}
return context.Users
.Where(u => u.Equals(model))
.Select(r => r.GetBindingModel());
}
public UserBindingModel? Insert(UserBindingModel model)
{
if (model is null)
{
return null;
}
var context = new Database();
var newUser = Models.User.ToUserFromBinding(model);
context.Users.Add(newUser);
context.SaveChanges();
return newUser.GetBindingModel();
}
public UserBindingModel? Update(UserBindingModel model)
{
var context = new Database();
var user = context.Users.FirstOrDefault(u => u.Id == model.Id);
if (user is null)
{
return null;
}
user.Update(model);
context.SaveChanges();
return user.GetBindingModel();
}
}
}