Add Method to delete whole recipe with their relations and include Mediafiles to Instruction by getting recipe

This commit is contained in:
franc
2025-05-13 14:45:39 +02:00
parent ff08b82611
commit 1c47b770b4
2 changed files with 45 additions and 0 deletions
@@ -18,5 +18,7 @@
Task<Recipe> CreateRecipeForCategoryAsync(Category category, string name, string description, Difficulty difficulty, int servings, TimeSpan preparationTime, TimeSpan cookingTime);
Task<IEnumerable<Recipe>> SearchInRecipesAndIngredients(string searchterm);
Task DeleteRecipeAsync(Guid recipeId);
}
}
@@ -38,6 +38,7 @@
.ThenInclude(ri => ri.Unit)
.Include(r => r.MediaFiles)
.Include(r => r.Instructions)
.ThenInclude(i => i.MediaFiles)
.FirstOrDefaultAsync(r => r.Id == recipeId);
}
@@ -182,5 +183,47 @@
.ThenInclude(ri => ri.Ingredient)
.ToListAsync();
}
public async Task DeleteRecipeAsync(Guid recipeId)
{
var recipe = await GetRecipeByIdAsync(recipeId);
if (recipe == null)
{
throw new InvalidDataException($"Rezept mit ID {recipeId} nicht gefunden.");
}
if (recipe.RecipeIngredients != null && recipe.RecipeIngredients.Any())
{
_context.RecipeIngredients.RemoveRange(recipe.RecipeIngredients);
}
if (recipe.Instructions != null && recipe.Instructions.Any())
{
foreach (var instruction in recipe.Instructions)
{
if (instruction.MediaFiles != null && instruction.MediaFiles.Any())
{
_context.MediaFiles.RemoveRange(instruction.MediaFiles);
}
}
_context.Instructions.RemoveRange(recipe.Instructions);
}
if (recipe.MediaFiles != null && recipe.MediaFiles.Any())
{
_context.MediaFiles.RemoveRange(recipe.MediaFiles);
}
if (recipe.Favorit != null && recipe.Favorit.Id != Guid.Empty)
{
_context.Remove(recipe.Favorit);
}
_context.Recipes.Remove(recipe);
await _context.SaveChangesAsync();
}
}
}