PIbd-23-Nasyrov-A.G.-Flower.../FlowerShopDatabaseImplement/FlowerStorage.cs

111 lines
3.6 KiB
C#
Raw Normal View History

2024-03-12 21:47:28 +04:00
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowerShopDatabaseImplement.Implements
{
public class FlowerStorage : IFlowerStorage
{
public List<FlowerViewModel> GetFullList()
{
using var context = new FlowerShopDataBase();
return context.Flowers
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<FlowerViewModel> GetFilteredList(FlowerSearchModel model)
{
if (string.IsNullOrEmpty(model.FlowerName))
{
return new();
}
using var context = new FlowerShopDataBase();
return context.Flowers.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.FlowerName.Contains(model.FlowerName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public FlowerViewModel? GetElement(FlowerSearchModel model)
{
if (string.IsNullOrEmpty(model.FlowerName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new FlowerShopDataBase();
return context.Flowers
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.FlowerName) &&
x.FlowerName == model.FlowerName) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public FlowerViewModel? Insert(FlowerBindingModel model)
{
using var context = new FlowerShopDataBase();
var newFlower = Flower.Create(context, model);
if (newFlower == null)
{
return null;
}
context.Flowers.Add(newFlower);
context.SaveChanges();
return newFlower.GetViewModel;
}
public FlowerViewModel? Update(FlowerBindingModel model)
{
using var context = new FlowerShopDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var flower = context.Flowers.FirstOrDefault(rec =>
rec.Id == model.Id);
if (flower == null)
{
return null;
}
flower.Update(model);
context.SaveChanges();
flower.UpdateComponents(context, model);
transaction.Commit();
return flower.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public FlowerViewModel? Delete(FlowerBindingModel model)
{
using var context = new FlowerShopDataBase();
var element = context.Flowers
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Flowers.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}