PIbd-22-Ismailov_SUBD/BlogDataModels/BlogDatabaseImplement/Implements/NewsStorage.cs
2023-05-18 21:34:36 +04:00

107 lines
3.1 KiB
C#

using BlogContracts.BindingModel;
using BlogContracts.SearchModels;
using BlogContracts.StorageContracts;
using BlogContracts.ViewModels;
using BlogDatabaseImplement.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlogDatabaseImplement.Implements
{
public class NewsStorage : INewsStorage
{
public NewsViewModel? Delete(NewsBindingModel model)
{
using var context = new BlogDatabase();
var element = context.News.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.News.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public NewsViewModel? GetElement(NewsSearchModel model)
{
if (string.IsNullOrEmpty(model.Title) &&
!model.Id.HasValue)
{
return null;
}
using var context = new BlogDatabase();
return context.News
.Include(x => x.Tags)
.ThenInclude(x => x.Tag)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Title) &&
x.Title == model.Title) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public List<NewsViewModel> GetFilteredList(NewsSearchModel model)
{
if (string.IsNullOrEmpty(model.Title))
{
return new();
}
using var context = new BlogDatabase();
return context.News
.Include(x => x.Tags)
.ThenInclude(x => x.Tag)
.Where(x => x.Title.Contains(model.Title))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<NewsViewModel> GetFullList()
{
using var context = new BlogDatabase();
return context.News
.Include(x => x.User)
.Include(x => x.Tags)
.ThenInclude(x => x.Tag)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public NewsViewModel? Insert(NewsBindingModel model)
{
using var context = new BlogDatabase();
var newNews = News.Create(context, model);
if (newNews == null)
{
return null;
}
context.News.Add(newNews);
context.SaveChanges();
return newNews.GetViewModel;
}
public NewsViewModel? Update(NewsBindingModel model)
{
using var context = new BlogDatabase();
var element = context.News
.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
return element.GetViewModel;
}
}
}