示例#1
0
        public void Seed()
        {
            var ensureCreated = _ctx.Database.EnsureCreated();

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

                var order = new Order
                {
                    OrderDate   = DateTime.Now,
                    OrderNumber = "12345",
                    Items       = new List <OrderItem>
                    {
                        new OrderItem {
                            Product = products.First(), Quantity = 5, UnitPrice = products.First().Price
                        }
                    }
                };

                _ctx.Orders.Add(order);

                _ctx.SaveChanges();
            }
        }
示例#2
0
        public async Task SeedAsync()
        {
            _dbContext.Database.EnsureCreated();

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

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

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

                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("Failed to create user in seeder");
                }
            }
            if (!_dbContext.Products.Any())
            {
                var filepath = Path.Combine(_hosting.ContentRootPath, "Data/Seed/art.json");
                var json     = File.ReadAllText(filepath);
                var products = JsonConvert.DeserializeObject <IEnumerable <Product> >(json);
                _dbContext.Products.AddRange(products);

                var order = _dbContext.Orders.Where(o => o.Id == 1).FirstOrDefault();
                if (order != null)
                {
                    order.User  = user;
                    order.Items = new List <OrderItem>()
                    {
                        new OrderItem()
                        {
                            Product   = products.First(),
                            Quantity  = 5,
                            UnitPrice = products.First().Price
                        }
                    };
                }

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