117 lines
3.5 KiB
C#
117 lines
3.5 KiB
C#
using UniversityContracts.BindingModels;
|
|
using UniversityContracts.StoragesContracts;
|
|
using UniversityContracts.ViewModels;
|
|
using UniversityDatabaseImplement;
|
|
using UniversityDatabaseImplement.Models;
|
|
|
|
namespace UniversityUniversityDatabaseImplement.Implements
|
|
{
|
|
public class DirectionStorage : IDirectionStorage
|
|
{
|
|
public void Delete(DirectionBindingModel model)
|
|
{
|
|
var context = new UniversityDatabase();
|
|
var direction = context.Directions.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (direction != null)
|
|
{
|
|
context.Directions.Remove(direction);
|
|
context.SaveChanges();
|
|
}
|
|
else
|
|
{
|
|
throw new Exception("Направление не найдено");
|
|
}
|
|
}
|
|
|
|
public DirectionViewModel GetElement(DirectionBindingModel model)
|
|
{
|
|
if (model == null)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new UniversityDatabase();
|
|
|
|
var direction = context.Directions
|
|
.ToList()
|
|
.FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name);
|
|
return direction != null ? CreateModel(direction) : null;
|
|
}
|
|
|
|
|
|
public List<DirectionViewModel> GetFilteredList(DirectionBindingModel model)
|
|
{
|
|
if (model == null)
|
|
{
|
|
return null;
|
|
}
|
|
using var context = new UniversityDatabase();
|
|
return context.Directions
|
|
.Where(rec => rec.Name.Contains(model.Name))
|
|
.Select(CreateModel)
|
|
.ToList();
|
|
}
|
|
|
|
public List<DirectionViewModel> GetFullList()
|
|
{
|
|
using var context = new UniversityDatabase();
|
|
return context.Directions
|
|
.Select(CreateModel)
|
|
.ToList();
|
|
}
|
|
|
|
public void Insert(DirectionBindingModel model)
|
|
{
|
|
var context = new UniversityDatabase();
|
|
var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
context.Directions.Add(CreateModel(model, new Direction()));
|
|
context.SaveChanges();
|
|
transaction.Commit();
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public void Update(DirectionBindingModel model)
|
|
{
|
|
var context = new UniversityDatabase();
|
|
var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
var direction = context.Directions.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (direction == null)
|
|
{
|
|
throw new Exception("Направление не найдено");
|
|
}
|
|
CreateModel(model, direction);
|
|
context.SaveChanges();
|
|
transaction.Commit();
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private static Direction CreateModel(DirectionBindingModel model, Direction direction)
|
|
{
|
|
direction.Name = model.Name;
|
|
return direction;
|
|
}
|
|
|
|
private static DirectionViewModel CreateModel(Direction direction)
|
|
{
|
|
return new DirectionViewModel
|
|
{
|
|
Id = direction.Id,
|
|
Name = direction.Name
|
|
};
|
|
}
|
|
}
|
|
}
|