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

86 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
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 ProjectStorage : IProjectStorage
{
public List<ProjectViewModel> GetFullList()
{
using var context = new TaskTrackerDatabase();
return context.Projects
.Select(x => x.GetViewModel)
.ToList();
}
public List<ProjectViewModel> GetFilteredList(ProjectSearchModel model)
{
if (string.IsNullOrEmpty(model.ProjectName))
{
return new();
}
using var context = new TaskTrackerDatabase();
return context.Projects
.Where(x => x.ProjectName.Contains(model.ProjectName))
.Select(x => x.GetViewModel)
.ToList();
}
public ProjectViewModel? GetElement(ProjectSearchModel model)
{
if (string.IsNullOrEmpty(model.ProjectName) && !model.Id.HasValue)
{
return null;
}
using var context = new TaskTrackerDatabase();
return context.Projects
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ProjectName) && x.ProjectName ==
model.ProjectName) || (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ProjectViewModel? Insert(ProjectBindingModel model)
{
var newProject = Project.Create(model);
if (newProject == null)
{
return null;
}
using var context = new TaskTrackerDatabase();
context.Projects.Add(newProject);
context.SaveChanges();
return newProject.GetViewModel;
}
public ProjectViewModel? Update(ProjectBindingModel model)
{
using var context = new TaskTrackerDatabase();
var project = context.Projects.FirstOrDefault(x => x.Id == model.Id);
if (project == null)
{
return null;
}
project.Update(model);
context.SaveChanges();
return project.GetViewModel;
}
public ProjectViewModel? Delete(ProjectBindingModel model)
{
using var context = new TaskTrackerDatabase();
var element = context.Projects.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Projects.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}