From 2f33951c4e10e52dee5938fb6e271fdd00b87cc8 Mon Sep 17 00:00:00 2001 From: franc Date: Wed, 16 Apr 2025 11:17:42 +0200 Subject: [PATCH] Change Search Logic --- .../Repositories/Recipe/IRecipeRepository.cs | 4 +- .../Repositories/Recipe/RecipeRepository.cs | 38 ++++++++----------- 2 files changed, 18 insertions(+), 24 deletions(-) diff --git a/Francesco.Recipes.World/Repositories/Recipe/IRecipeRepository.cs b/Francesco.Recipes.World/Repositories/Recipe/IRecipeRepository.cs index 03414e1..0f1d8a3 100644 --- a/Francesco.Recipes.World/Repositories/Recipe/IRecipeRepository.cs +++ b/Francesco.Recipes.World/Repositories/Recipe/IRecipeRepository.cs @@ -13,10 +13,10 @@ Task RemoveIngredientFromRecipeAsync(Guid recipeId, Guid ingredientId); - Task> GetRecipesByNameAndIngredientAsync(string name, string ingredient); - Task> GetRecipesByDifficultyAsync(Difficulty? difficulty); Task CreateRecipeForCategoryAsync(Category category, string name, string description, Difficulty difficulty, int servings, TimeSpan preparationTime, TimeSpan cookingTime); + + Task> GetRecipesBySearchQueryAsync(string query); } } diff --git a/Francesco.Recipes.World/Repositories/Recipe/RecipeRepository.cs b/Francesco.Recipes.World/Repositories/Recipe/RecipeRepository.cs index f71303f..41f7927 100644 --- a/Francesco.Recipes.World/Repositories/Recipe/RecipeRepository.cs +++ b/Francesco.Recipes.World/Repositories/Recipe/RecipeRepository.cs @@ -147,30 +147,24 @@ await _context.SaveChangesAsync(); } - public async Task> GetRecipesByNameAndIngredientAsync(string name, string ingredient) + public async Task> GetRecipesBySearchQueryAsync(string query) { - var query = _context.Recipes + if (string.IsNullOrWhiteSpace(query)) + { + return await _context.Recipes + .Include(r => r.RecipeIngredients) + .ThenInclude(ri => ri.Ingredient) + .ToListAsync(); + } + + query = query.ToLower(); + + return await _context.Recipes .Include(r => r.RecipeIngredients) - .ThenInclude(ri => ri.Ingredient) - .AsQueryable(); - - if (!string.IsNullOrWhiteSpace(name)) - { - query = query.Where(r => r.Name.Contains(name, StringComparison.OrdinalIgnoreCase)); - } - - if (!string.IsNullOrWhiteSpace(ingredient)) - { - var ingredientMatches = await _ingredientRepository.GetIngredientsByNameAsync(ingredient); - var ingredientIds = ingredientMatches.Select(i => i.Id).ToList(); - - if (ingredientIds.Any()) - { - query = query.Where(r => r.RecipeIngredients.Any(ri => ingredientIds.Contains(ri.Ingredient.Id))); - } - } - - return await query.ToListAsync(); + .ThenInclude(ri => ri.Ingredient) + .Where(r => r.Name.ToLower().Contains(query) || + r.RecipeIngredients.Any(ri => ri.Ingredient.Name.ToLower().Contains(query))) + .ToListAsync(); } public async Task> GetRecipesByDifficultyAsync(Difficulty? difficulty)