PIbd-23_Mochalov_D.V._LawFirm/LawFirm/LawFirmDatabaseImplement/Implements/DocumentStorage.cs

132 lines
4.2 KiB
C#

using LawFirmContracts.BindingModels;
using LawFirmContracts.SearchModels;
using LawFirmContracts.StorageContracts;
using LawFirmContracts.ViewModels;
using LawFirmDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
namespace LawFirmDatabaseImplement.Implements
{
public class DocumentStorage : IDocumentStorage
{
public DocumentViewModel? GetElement(DocumentSearchModel model)
{
if (string.IsNullOrEmpty(model.DocumentName) && !model.Id.HasValue)
{
return null;
}
using var context = new LawFirmDatabase();
return context.Documents.Include(x => x.Blanks)
.ThenInclude(x => x.Blank)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.DocumentName) &&
x.DocumentName == model.DocumentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<DocumentViewModel> GetFilteredList(DocumentSearchModel model)
{
if (string.IsNullOrEmpty(model.DocumentName))
{
return new();
}
using var context = new LawFirmDatabase();
return context.Documents
.Include(x => x.Blanks)
.ThenInclude(x => x.Blank)
.Where(x => x.DocumentName.Contains(model.DocumentName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<DocumentViewModel> GetFullList()
{
using var context = new LawFirmDatabase();
return context.Documents
.Include(x => x.Blanks)
.ThenInclude(x => x.Blank)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public DocumentViewModel? Insert(DocumentBindingModel model)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var newDoc = Document.Create(context, model);
if (newDoc == null)
{
transaction.Rollback();
return null;
}
context.Documents.Add(newDoc);
context.SaveChanges();
context.Database.CommitTransaction();
return newDoc.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public DocumentViewModel? Update(DocumentBindingModel model)
{
using var context = new LawFirmDatabase();
using var transaction = context.Database.BeginTransaction();
{
try
{
var document = context.Documents.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
transaction.Rollback();
return null;
}
document.Update(model);
document.UpdateComponents(context, model);
context.SaveChanges();
context.Database.CommitTransaction();
return document.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
return null;
}
}
}
public DocumentViewModel? Delete(DocumentBindingModel model)
{
using var context = new LawFirmDatabase();
var element = context.Documents.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Documents.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}