public async Task AddRecipe(RecipeAddModel model, string currentUserName) { var filePath = ""; if(model.Image != null) { filePath = await this.UploadFile(model.Image); } else { filePath = "noimage.png"; } var user = this.dbContext .Users .FirstOrDefault(u => u.UserName == currentUserName); var userId = user.Id; if(user == null) { throw new ArgumentException("User not found"); } var course = this.dbContext .Courses .FirstOrDefault(c => c.Name == model.Course); if(course == null) { throw new ArgumentNullException(nameof(model.Course)); } var cat = this.dbContext .Categories .FirstOrDefault(c => c.Name == model.Category); if (cat == null) { throw new ArgumentNullException(nameof(model.Category)); } var recipe = new Recipe { Name = model.Name, Description = model.Description, Preparation = model.Preparation, Servings = model.Servings, PrepTime = model.PrepTime, CookingTime = model.CookingTime, ImageUrl = filePath, AuthorId = userId, Author = user, AddedOn = DateTime.Now, CourseId = course.Id, CategoryId = cat.Id, Course = course, Category = cat }; var ingredients = new List<RecipeIngredient>(); foreach (var ingr in model.Ingredients) { if(!this.dbContext.Measurements .Any(m => m.Name == ingr.Measurement)) { await this.dbContext.Measurements .AddAsync(new Measurement { Name = ingr.Measurement }); await this.dbContext.SaveChangesAsync(); } var measurement = this.dbContext .Measurements .FirstOrDefault(m => m.Name == ingr.Measurement); var quantity = ingr.Quantity; if(!this.dbContext.Ingredients.Any(i => i.Name == ingr.Name)) { await this.dbContext.Ingredients.AddAsync(new Ingredient { Name = ingr.Name }); await this.dbContext.SaveChangesAsync(); } var ingredient = this.dbContext .Ingredients .FirstOrDefault(i => i.Name == ingr.Name); ingredients.Add(new RecipeIngredient { Measurement = measurement, Quantity = quantity, IngredientId = ingredient.Id }); } recipe.Ingredients = ingredients; this.dbContext.Add(recipe); this.dbContext.SaveChanges(); }