| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- using DutchTreat.Data.Entities;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Identity;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- namespace DutchTreat.Data
- {
- public class DutchSeeder
- {
- private readonly DutchContext _ctx;
- private readonly IWebHostEnvironment _env;
- private readonly UserManager<StoreUser> _userManager;
- public DutchSeeder(DutchContext ctx, IWebHostEnvironment env, UserManager<StoreUser> userManager)
- {
- _ctx = ctx;
- _env = env;
- _userManager = userManager;
- }
- public async Task SeedAsync()
- {
- _ctx.Database.EnsureCreated();
- StoreUser user = await _userManager.FindByEmailAsync("shawn@dutchTreat.com");
- if (user == null)
- {
- user = new StoreUser()
- {
- FirstName = "Shawn",
- LastName = "Wildermuth",
- Email = "shawn@dutchtreat.com",
- UserName = "shawn@dutchtreat.com"
- };
- var result = await _userManager.CreateAsync(user, "P@ssw0rd!");
- if (result != IdentityResult.Success)
- {
- throw new InvalidOperationException("Could not create new user in seeder");
- }
- }
- if (!_ctx.Products.Any())
- {
- //Need to create sample data
- var filePath = Path.Combine(_env.ContentRootPath, "Data/art.json");
- var json = File.ReadAllText(filePath);
- var products = JsonSerializer.Deserialize<IEnumerable<Product>>(json);
- _ctx.AddRange(products);
- 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
- }
- }
- };
- _ctx.Orders.Add(order);
- _ctx.SaveChanges();
- }
- }
- }
- }
|