Exemplo n.º 1
0
        public async Task InsertDishedIntoDb()
        {
            var dishDb = await _dishesRepository.CheckIfExistsItems();

            if (dishDb)
            {
                return;
            }
            var projectRootPath   = _hostingEnvironment.ContentRootPath;
            var fullFileDirectory = Path.Combine(projectRootPath, StaticDocumentsDirectories.JsonFiles);

            if (!Directory.Exists(fullFileDirectory))
            {
                throw new ApplicationException(Errors.DirectoryDoesNotExist);
            }
            var fullFileName = Path.Combine(fullFileDirectory, "dishes-sample-data.json");

            if (!File.Exists(fullFileName))
            {
                throw new ApplicationException(Errors.FileDoesNotExist);
            }
            var jsonString = File.ReadAllText(fullFileName);
            var jsonModel  = JsonConvert.DeserializeObject <List <JsonDishes> >(jsonString);

            foreach (var item in jsonModel)
            {
                var dish = new Dishes
                {
                    Id       = item.id,
                    Name     = item.name,
                    ParentId = item.parentId
                };
                dish.UpdatedOn = dish.UpdatedOn = DateTime.Parse((item.updatedOn).ToString());
                await _dishesRepository.Create(dish);

                foreach (var item2 in item.ingredients)
                {
                    var ingredient = new DishIngredient
                    {
                        DishesId     = dish.Id,
                        Amount       = item2.amount,
                        IngredientId = item2.ingredientId
                    };

                    await _dishesIngredientsRepository.Create(ingredient);
                }
                await _dishesRepository.Save();
            }
        }