SUBD_SushiBar/SushiBar/SushiBarDatabaseImplement/Implements/TaskStorage.cs

97 lines
3.1 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore;
using SushiBarContracts.BindingModels;
using SushiBarContracts.SearchModels;
using SushiBarContracts.StoragesContracts;
using SushiBarContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SushiBarDatabaseImplement.Implements
{
public class TaskStorage : ITaskStorage
{
2024-05-07 21:53:37 +04:00
public void ClearEntity()
{
using var context = new SushiBarDatabase();
string deleteAllQuery = "DELETE FROM \"Tasks\"";
context.Database.ExecuteSqlRaw(deleteAllQuery);
}
public TaskViewModel? Delete(TaskBindingModel model)
{
using var context = new SushiBarDatabase();
var element = context.Tasks.Include(x => x.Menus).FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Tasks.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public TaskViewModel? GetElement(TaskSearchModel model)
{
using var context = new SushiBarDatabase();
return context.Tasks.Include(x => x.Menus).ThenInclude(x => x.Menu).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<TaskViewModel> GetFilteredList(TaskSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new SushiBarDatabase();
return context.Tasks.Include(x => x.Menus).ThenInclude(x => x.Menu).Where(x => x.Id == model.Id).ToList().Select(x => x.GetViewModel).ToList();
}
public List<TaskViewModel> GetFullList()
{
using var context = new SushiBarDatabase();
return context.Tasks.Include(x => x.Menus).ThenInclude(x => x.Menu).ToList().Select(x => x.GetViewModel).ToList();
}
public TaskViewModel? Insert(TaskBindingModel model)
{
using var context = new SushiBarDatabase();
var newTask = Models.Task.Create(context, model);
if (newTask == null)
{
return null;
}
context.Tasks.Add(newTask);
context.SaveChanges();
return newTask.GetViewModel;
}
public TaskViewModel? Update(TaskBindingModel model)
{
using var context = new SushiBarDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var task = context.Tasks.FirstOrDefault(x => x.Id == model.Id);
if (task == null)
{
return null;
}
task.Update(model);
context.SaveChanges();
//task.UpdateMenus(context, model);
transaction.Commit();
return task.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}