88 lines
2.7 KiB
C#
88 lines
2.7 KiB
C#
using BookContract.BindingModels;
|
|
using BookContract.StorageContracts;
|
|
using BookContract.ViewModels;
|
|
using BookDatabaseImplement.Model;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace BookDatabaseImplement.Implements
|
|
{
|
|
public class HistoryStorage : IHistoryStorage
|
|
{
|
|
private History CreateModel(HistoryBindingModel model, History history)
|
|
{
|
|
history.BookId = model.BookId;
|
|
history.ReaderId = model.ReaderId;
|
|
history.DateBorrowed = model.DateBorrowed;
|
|
return history;
|
|
}
|
|
|
|
private HistoryViewModel CreateModel(History history)
|
|
{
|
|
return new HistoryViewModel
|
|
{
|
|
Id = history.Id,
|
|
BookId = history.BookId,
|
|
ReaderId = history.ReaderId,
|
|
DateBorrowed = history.DateBorrowed
|
|
};
|
|
}
|
|
|
|
public List<HistoryViewModel> GetFullList()
|
|
{
|
|
using var context = new BookLibraryDatabase();
|
|
return context.Histories.ToList().Select(CreateModel).ToList();
|
|
}
|
|
|
|
public List<HistoryViewModel> GetHistoryByBookId(int bookId)
|
|
{
|
|
using var context = new BookLibraryDatabase();
|
|
return context.Histories
|
|
.Where(history => history.BookId == bookId)
|
|
.ToList().Select(CreateModel).ToList();
|
|
}
|
|
|
|
public HistoryViewModel? GetElement(HistoryBindingModel model)
|
|
{
|
|
using var context = new BookLibraryDatabase();
|
|
var history = context.Histories.FirstOrDefault(rec => rec.Id == model.Id);
|
|
return history != null ? CreateModel(history) : null;
|
|
}
|
|
|
|
public void Insert(HistoryBindingModel model)
|
|
{
|
|
using var context = new BookLibraryDatabase();
|
|
using var transaction = context.Database.BeginTransaction();
|
|
try
|
|
{
|
|
context.Histories.Add(CreateModel(model, new History()));
|
|
context.SaveChanges();
|
|
transaction.Commit();
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public void Delete(HistoryBindingModel model)
|
|
{
|
|
using var context = new BookLibraryDatabase();
|
|
var history = context.Histories.FirstOrDefault(rec => rec.Id == model.Id);
|
|
if (history != null)
|
|
{
|
|
context.Histories.Remove(history);
|
|
context.SaveChanges();
|
|
}
|
|
else
|
|
{
|
|
throw new Exception("Запись истории не найдена");
|
|
}
|
|
}
|
|
}
|
|
}
|