using Microsoft.EntityFrameworkCore; using SchoolAgainStudyContracts.BindingModel; using SchoolAgainStudyContracts.SearchModel; using SchoolAgainStudyContracts.StorageContracts; using SchoolAgainStudyContracts.ViewModel; using SchoolAgainStudyDataBaseImplements.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SchoolAgainStudyDataBaseImplements.Implements { public class DiyStorage : IDiyStorage { public List GetFullList() { using var context = new SchoolDataBase(); return context.Diys .Include(x => x.Interests) .ThenInclude(x => x.Interest) .ToList() .Select(x => x.GetViewModel) .ToList(); } public List GetFilteredList(DiySearchModel model) { if(!model.StudentId.HasValue) { return new(); } using var context = new SchoolDataBase(); if(model.DateFrom.HasValue && model.DateTo.HasValue && model.StudentId.HasValue) { return context.Diys .Include(x => x.Interests) .ThenInclude(x => x.Interest) .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo && x.StudentId == model.StudentId) .ToList() .Select(x => x.GetViewModel) .ToList(); } return context.Diys .Include(x => x.Interests) .ThenInclude(x => x.Interest) .Where(x => x.StudentId == model.StudentId ) .ToList() .Select(x => x.GetViewModel) .ToList(); } public DiyViewModel? GetElement(DiySearchModel model) { if (string.IsNullOrEmpty(model.Title) && !model.Id.HasValue && !model.StudentId.HasValue) { return null; } using var context = new SchoolDataBase(); if(!string.IsNullOrEmpty(model.Title)&& model.StudentId.HasValue) return context.Diys .Include(x => x.Interests) .ThenInclude(x => x.Interest) .FirstOrDefault(x => x.Title.Equals(model.Title) && x.StudentId==model.StudentId) ?.GetViewModel; return context.Diys .Include(x => x.Interests) .ThenInclude(x => x.Interest) .FirstOrDefault(x => x.Id == model.Id) ?.GetViewModel; } public DiyViewModel? Insert(DiyBindingModel model) { using var context = new SchoolDataBase(); var newDiy = Diy.Create(context, model); if (newDiy == null) { return null; } context.Diys.Add(newDiy); context.SaveChanges(); return newDiy.GetViewModel; } public DiyViewModel? Update(DiyBindingModel model) { using var context = new SchoolDataBase(); using var transaction = context.Database.BeginTransaction(); try { var diy = context.Diys.FirstOrDefault(rec => rec.Id == model.Id); if (diy == null) { return null; } diy.Update(model); context.SaveChanges(); diy.UpdateInterests(context, model); transaction.Commit(); return diy.GetViewModel; } catch { transaction.Rollback(); throw; } } public DiyViewModel? Delete(DiyBindingModel model) { using var context = new SchoolDataBase(); var element = context.Diys .Include(x => x.Interests) .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Diys.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }