PIbd-33_Dyakonov_R_R_COP_14/DatabaseImplement/Implements/ManufacturerStorage.cs
dyakonovr f8fc0b4584 done
2024-10-28 20:58:57 +04:00

122 lines
2.8 KiB
C#

using Contracts.BindingModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseImplement.Implements
{
public class ManufacturerStorage : IManufacturerStorage
{
public void Delete(ManufacturerBindingModel model)
{
var context = new ProductsDatabase();
var Manufacturer = context.Manufacturers.FirstOrDefault(rec => rec.Id == model.Id);
if (Manufacturer != null)
{
context.Manufacturers.Remove(Manufacturer);
context.SaveChanges();
}
else
{
throw new Exception("Производитель не найден");
}
}
public ManufacturerViewModel GetElement(ManufacturerBindingModel model)
{
if (model == null)
{
return null;
}
using var context = new ProductsDatabase();
var manufacturer = context.Manufacturers
.ToList()
.FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name);
return manufacturer != null ? CreateModel(manufacturer) : null;
}
public List<ManufacturerViewModel> GetFilteredList(ManufacturerBindingModel model)
{
if (model == null)
{
return null;
}
using var context = new ProductsDatabase();
return context.Manufacturers
.Where(rec => rec.Name.Contains(model.Name))
.Select(CreateModel)
.ToList();
}
public List<ManufacturerViewModel> GetFullList()
{
using var context = new ProductsDatabase();
return context.Manufacturers
.Select(CreateModel)
.ToList();
}
public void Insert(ManufacturerBindingModel model)
{
var context = new ProductsDatabase();
var transaction = context.Database.BeginTransaction();
try
{
context.Manufacturers.Add(CreateModel(model, new Manufacturer()));
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Update(ManufacturerBindingModel model)
{
var context = new ProductsDatabase();
var transaction = context.Database.BeginTransaction();
try
{
var Manufacturer = context.Manufacturers.FirstOrDefault(rec => rec.Id == model.Id);
if (Manufacturer == null)
{
throw new Exception("Производитель не найден");
}
CreateModel(model, Manufacturer);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
private static Manufacturer CreateModel(ManufacturerBindingModel model, Manufacturer Manufacturer)
{
Manufacturer.Name = model.Name;
return Manufacturer;
}
private static ManufacturerViewModel CreateModel(Manufacturer Manufacturer)
{
return new ManufacturerViewModel
{
Id = Manufacturer.Id,
Name = Manufacturer.Name
};
}
}
}