You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
WF-PmAPI/WF_EF_Api/Contextlib/DbImagesManager.cs

102 lines
3.5 KiB

using Entity;
using Microsoft.EntityFrameworkCore;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Contextlib
{
public class DbImagesManager : IImagesService<Images>
{
private WTFContext _context;
public DbImagesManager(WTFContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null.");
}
public async Task AddImage(Images image)
{
await _context.AddAsync(image);
await _context.SaveChangesAsync();
}
public async Task<PaginationResult<Images>> GetAllImage()
{
var images = await _context.images.ToListAsync();
return new PaginationResult<Images>(images.Count, 0, images.Count, images);
}
public async Task<Images> GetImageById(int id)
{
var image = await _context.images.Where(x => x.Id == id).FirstOrDefaultAsync();
if (image == null)
{
throw new KeyNotFoundException($"No image found with the given ID: {id}.");
}
return image;
}
public async Task<int> GetLastImageId()
{
var last = await _context.images.OrderByDescending(x => x.Id).FirstOrDefaultAsync();
if (last == null)
{
return 0;
}
return last.Id;
}
public async Task<PaginationResult<Images>> GetSomeImage(int index, int pageSize)
{
var images = await _context.images.ToListAsync();
if (!images.Any())
{
throw new KeyNotFoundException($"No images found");
}
if ((index * pageSize + pageSize) > images.Count)
{
if (pageSize > images.Count)
{
return new PaginationResult<Images>(images.Count(), index, pageSize, images);
}
else
{
return new PaginationResult<Images>(pageSize, index, pageSize, images.Skip(index * pageSize - (((index * pageSize) + pageSize) - images.Count)).Take(pageSize).ToList());
}
}
return new PaginationResult<Images>(images.Count, index, pageSize, images.Skip(index * pageSize).Take(pageSize).ToList());
}
public async Task RemoveImage(int id)
{
var image = await _context.images.Where(x => x.Id == id).FirstOrDefaultAsync();
if (image == null)
{
throw new KeyNotFoundException($"No image found with the given ID: {id}.");
}
_context.images.Remove(image);
await _context.SaveChangesAsync();
}
public async Task UpdateImage(int id, Images image)
{
var img = await _context.images.Where(x => x.Id == id).FirstOrDefaultAsync();
if (image == null)
{
throw new ArgumentNullException(nameof(image), "The updated image data cannot be null.");
}
if (img == null)
{
throw new KeyNotFoundException($"No image found with the given ID: {id}.");
}
img.ImgPath = image.ImgPath;
await _context.SaveChangesAsync();
}
}
}