88 lines
2.2 KiB
C#
88 lines
2.2 KiB
C#
using CarServiceContracts.BindingModels;
|
|
using CarServiceContracts.SearchModels;
|
|
using CarServiceContracts.StorageContracts;
|
|
using CarServiceContracts.ViewModels;
|
|
using CarServiceDatabase.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace CarServiceDatabase.Implements
|
|
{
|
|
public class ItemStorage : IItemStorage
|
|
{
|
|
public List<ItemViewModel> GetFullList()
|
|
{
|
|
using var context = new CarServiceDbContext();
|
|
return context.Items
|
|
.Include(x => x.Worker)
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
public List<ItemViewModel> GetFilteredList(ItemSearchModel model)
|
|
{
|
|
using var context = new CarServiceDbContext();
|
|
return context.Items
|
|
.Where(x => x.Id == model.Id)
|
|
.Include(x => x.Worker)
|
|
.Select(x => x.GetViewModel)
|
|
.ToList();
|
|
}
|
|
public ItemViewModel? GetElement(ItemSearchModel model)
|
|
{
|
|
if (model == null)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new CarServiceDbContext();
|
|
if (model.Id.HasValue)//сначала ищем по Id
|
|
{
|
|
return context.Items
|
|
.Include(x => x.Worker)
|
|
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
|
|
}
|
|
if (!string.IsNullOrEmpty(model.Name))//затем по названию
|
|
{
|
|
return context.Items
|
|
.Include(x => x.Worker)
|
|
.FirstOrDefault(x => x.Name == model.Name)?.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
public ItemViewModel? Insert(ItemBindingModel model)
|
|
{
|
|
using var context = new CarServiceDbContext();
|
|
var newItem = Item.Create(context, model);
|
|
if (newItem != null)
|
|
{
|
|
context.Items.Add(newItem);
|
|
context.SaveChanges();
|
|
return newItem.GetViewModel;
|
|
}
|
|
return null;
|
|
}
|
|
public ItemViewModel? Update(ItemBindingModel model)
|
|
{
|
|
using var context = new CarServiceDbContext();
|
|
var item = context.Items.FirstOrDefault(x => x.Id == model.Id);
|
|
if (item == null)
|
|
{
|
|
return null;
|
|
}
|
|
item.Update(context, model);
|
|
context.SaveChanges();
|
|
return item.GetViewModel;
|
|
}
|
|
public ItemViewModel? Delete(ItemBindingModel model)
|
|
{
|
|
using var context = new CarServiceDbContext();
|
|
var item = context.Items.FirstOrDefault(x => x.Id == model.Id);
|
|
if (item == null)
|
|
{
|
|
return null;
|
|
}
|
|
context.Items.Remove(item);
|
|
context.SaveChanges();
|
|
return item.GetViewModel;
|
|
}
|
|
}
|
|
}
|