From b05645d526e75ff97d44c360b3dc34fa8e395b3a Mon Sep 17 00:00:00 2001 From: SysAdmin Date: Sat, 4 Oct 2025 17:48:30 +0100 Subject: [PATCH] Fix: Load navigation properties before projection to ensure variants are included MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Problem**: EF Core was not materializing Variants navigation property when using .Select() projection directly in the query. The .Include() was being ignored. **Solution**: Changed approach to: 1. Load entities with .Include() + .ToListAsync() first 2. Then project to DTO with in-memory .Select() This ensures navigation properties are fully loaded before mapping to DTOs. **Impact**: Variants will now properly appear in all product API responses. 🤖 Generated with Claude Code https://claude.com/claude-code Co-Authored-By: Claude --- LittleShop/Services/ProductService.cs | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/LittleShop/Services/ProductService.cs b/LittleShop/Services/ProductService.cs index 1cdad13..86e8cc0 100644 --- a/LittleShop/Services/ProductService.cs +++ b/LittleShop/Services/ProductService.cs @@ -18,13 +18,16 @@ public class ProductService : IProductService public async Task> GetAllProductsAsync() { - return await _context.Products + var products = await _context.Products .Include(p => p.Category) .Include(p => p.Photos) .Include(p => p.MultiBuys) .Include(p => p.Variants) .Where(p => p.IsActive) - .Select(p => new ProductDto + .AsNoTracking() + .ToListAsync(); + + return products.Select(p => new ProductDto { Id = p.Id, Name = p.Name, @@ -73,19 +76,21 @@ public class ProductService : IProductService CreatedAt = v.CreatedAt, UpdatedAt = v.UpdatedAt }).ToList() - }) - .ToListAsync(); + }).ToList(); } public async Task> GetProductsByCategoryAsync(Guid categoryId) { - return await _context.Products + var products = await _context.Products .Include(p => p.Category) .Include(p => p.Photos) .Include(p => p.MultiBuys) .Include(p => p.Variants) .Where(p => p.IsActive && p.CategoryId == categoryId) - .Select(p => new ProductDto + .AsNoTracking() + .ToListAsync(); + + return products.Select(p => new ProductDto { Id = p.Id, Name = p.Name, @@ -134,8 +139,7 @@ public class ProductService : IProductService CreatedAt = v.CreatedAt, UpdatedAt = v.UpdatedAt }).ToList() - }) - .ToListAsync(); + }).ToList(); } public async Task GetProductByIdAsync(Guid id)