// GET: Entries/Create public async Task <IActionResult> Create() { var ing = await _context.Ingredients.ToListAsync(); var rec = await _context.Recipes.Include(r => r.RecipeIngredients).ThenInclude(r => r.Ingredient).ToListAsync(); var model = new EntriesCreateModel { Ingredients = ing, Recipes = rec, UserProfileId = HttpContext.Session.GetInt32("Id").GetValueOrDefault() }; foreach (var item in ing) { model.EntryIngredients.Add(new EntryIngredient { Ingredient = item, IngredientQuantity = 0 }); } foreach (var item in rec) { item.IsNew = false; model.EntryRecipes.Add(new EntryRecipe { Recipe = item }); } return(View(model)); }
public async Task <IActionResult> Create(EntriesCreateModel entry, int uid) { if (HttpContext.Session.GetInt32("Id") == null) { return(RedirectToAction(nameof(UserProfileController.SignIn))); } if (true /*ModelState.IsValid*/) { entry.UserProfileId = (int)HttpContext.Session.GetInt32("Id"); ICollection <EntryIngredient> ing = new List <EntryIngredient>(); ICollection <EntryRecipe> rec = new List <EntryRecipe>(); var en = new Entry { Date = entry.Date, UserProfileId = entry.UserProfileId, }; _context.Add(en); _context.SaveChanges(); foreach (var item in entry.EntryRecipes.Where(i => i.Recipe.IsNew == true)) { rec.Add(new EntryRecipe { RecipeId = item.Recipe.Id, Entry = en, EntryId = en.Id }); } _context.EntryRecipes.AddRange(rec); _context.SaveChanges(); foreach (var item in entry.EntryIngredients.Where(i => i.IngredientQuantity > 0)) { ing.Add(new EntryIngredient { IngredientId = item.Ingredient.Id, IngredientQuantity = item.IngredientQuantity, Entry = en, EntryId = en.Id }); } _context.EntryIngredients.AddRange(ing); _context.SaveChanges(); return(RedirectToAction(nameof(Index))); } return(View(entry)); }