Exemplo n.º 1
0
        public async Task SeedASync()
        {
            _ctx.Database.EnsureCreated();

            StoreUser user = await _userManager.FindByEmailAsync("*****@*****.**");

            if (user == null)
            {
                user = new StoreUser()
                {
                    FirstName = "Matt",
                    LastName  = "Hensley",
                    Email     = "*****@*****.**",
                    UserName  = "******"
                };

                var result = await _userManager.CreateAsync(user, "Password1!");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Could not create new user in seeder");
                }
            }

            if (!_ctx.Products.Any())
            {
                // next bit extracts the products from a json file and stores them in a variable
                var filepath = Path.Combine(_hosting.ContentRootPath, "Data/products.json");
                var json     = File.ReadAllText(filepath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                _ctx.Products.AddRange(products);

                // next bit stores an order (already added in the migration) from GoldiesContext
                var order = _ctx.Orders.Where(o => o.Id == 1).FirstOrDefault();
                if (order != null)
                {
                    // Next bit adds some sample items to the order:
                    order.User  = user;
                    order.Items = new List <OrderItem>()
                    {
                        new OrderItem()
                        {
                            Product   = products.First(),
                            Quantity  = 5,
                            UnitPrice = products.First().Price
                        }
                    };
                }

                _ctx.SaveChanges();
            }
        }
 public bool SaveAll()
 {
     return(_ctx.SaveChanges() > 0);
 }