Beispiel #1
0
        public async Task Seed()
        {
            // Double check if the db is created (avoid some critical errors)
            _context.Database.EnsureCreated();

            // Create sample datas

            // User
            var user = await _userManager.FindByEmailAsync("*****@*****.**");

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

                var result = await _userManager.CreateAsync(user, "P@ssw0rd!");

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Failed to create default user");
                }
            }

            if (!_context.Products.Any())
            {
                // Products
                var filePath = Path.Combine(_hosting.ContentRootPath, "Data/sample.json");
                var json     = File.ReadAllText(filePath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                _context.Products.AddRange(products);

                if (!_context.Orders.Any())
                {
                    // Order and OrderItem
                    var order = new Order()
                    {
                        OrderDate   = DateTime.Now,
                        OrderNumber = "12345",
                        User        = user,
                        Items       = new List <OrderItem>()
                        {
                            new OrderItem()
                            {
                                Product   = products.First(),
                                Quantity  = 5,
                                UnitPrice = products.First().Price
                            }
                        }
                    };
                    _context.Orders.Add(order);
                }

                _context.SaveChanges();
            }
        }
Beispiel #2
0
 public bool SaveAll()
 {
     // Check if something changed before saving (> 0)
     return(_ctx.SaveChanges() > 0);
 }