Included navigation fields in get queries

This commit is contained in:
Khwezi Mngoma
2026-05-25 23:00:17 +02:00
parent d55bf4f82f
commit 4a85d01d1a
8 changed files with 73 additions and 22 deletions
@@ -74,7 +74,7 @@ public class ProductService(IDbContextFactory<MidrandBooksDbContext> contextFact
if (!string.IsNullOrWhiteSpace(filter.SerialNumber))
query = query.Where(p => p.Metadata!.SerialNumber == filter.SerialNumber);
if (filter.MinPrice > 0)
query = query.Where(p => p.Prices!.Any(pr => pr.Amount >= filter.MinPrice && pr.Amount <= filter.MaxPrice));
@@ -96,7 +96,7 @@ public class ProductService(IDbContextFactory<MidrandBooksDbContext> contextFact
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(!await context.Products.AnyAsync(p => p.Id == productId, cancellationToken))
if (!await context.Products.AnyAsync(p => p.Id == productId, cancellationToken))
return Result.Fail<long>($"Product with ID {productId} does not exist.");
var existingPrices = await context.Prices.Where(p => p.ProductId == productId).ToListAsync(cancellationToken);
@@ -133,10 +133,10 @@ public class ProductService(IDbContextFactory<MidrandBooksDbContext> contextFact
{
await using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
if(await context.Products.AnyAsync(p => p.Name == request.Name, cancellationToken))
if (await context.Products.AnyAsync(p => p.Name == request.Name, cancellationToken))
return Result.Fail<long>("A product with the same name already exists.");
if(request.Metadata is not null)
if (request.Metadata is not null)
if (await context.Products.AnyAsync(p => p.Metadata!.SerialNumber == request.Metadata.SerialNumber, cancellationToken))
return Result.Fail<long>("A product with the same metadata already exists.");
@@ -223,7 +223,7 @@ public class ProductService(IDbContextFactory<MidrandBooksDbContext> contextFact
}
}
public async ValueTask<Result<Product[]>> GetProductsAsync(DateRange range, CancellationToken cancellationToken = default)
public async ValueTask<Result<Product[]>> GetProductsAsync(int offset, DateRange range, CancellationToken cancellationToken = default)
{
try
{
@@ -234,11 +234,14 @@ public class ProductService(IDbContextFactory<MidrandBooksDbContext> contextFact
var products = await context.Products
.AsNoTracking()
.Include(p => p.Prices)
.OrderByDescending(p => p.CreatedAt)
.ThenBy(p => p.UpdatedAt)
.ThenByDescending(p => p.UpdatedAt)
.Where(p => p.CreatedAt >= fromDate && p.CreatedAt <= toDate)
.Skip(offset)
.Take(range.MaxRecords)
.ToArrayAsync(cancellationToken);
.AsSplitQuery()
.ToArrayAsync(cancellationToken);
return await context.SaveChangesAsync(cancellationToken) > 0
? Result.Ok(products.Select(p => p.ToModel()).ToArray())