DutchSeeder.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using DutchTreat.Data.Entities;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.Identity;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. namespace DutchTreat.Data
  12. {
  13. public class DutchSeeder
  14. {
  15. private readonly DutchContext _ctx;
  16. private readonly IWebHostEnvironment _env;
  17. private readonly UserManager<StoreUser> _userManager;
  18. public DutchSeeder(DutchContext ctx, IWebHostEnvironment env, UserManager<StoreUser> userManager)
  19. {
  20. _ctx = ctx;
  21. _env = env;
  22. _userManager = userManager;
  23. }
  24. public async Task SeedAsync()
  25. {
  26. _ctx.Database.EnsureCreated();
  27. StoreUser user = await _userManager.FindByEmailAsync("shawn@dutchTreat.com");
  28. if (user == null)
  29. {
  30. user = new StoreUser()
  31. {
  32. FirstName = "Shawn",
  33. LastName = "Wildermuth",
  34. Email = "shawn@dutchtreat.com",
  35. UserName = "shawn@dutchtreat.com"
  36. };
  37. var result = await _userManager.CreateAsync(user, "P@ssw0rd!");
  38. if (result != IdentityResult.Success)
  39. {
  40. throw new InvalidOperationException("Could not create new user in seeder");
  41. }
  42. }
  43. if (!_ctx.Products.Any())
  44. {
  45. //Need to create sample data
  46. var filePath = Path.Combine(_env.ContentRootPath, "Data/art.json");
  47. var json = File.ReadAllText(filePath);
  48. var products = JsonSerializer.Deserialize<IEnumerable<Product>>(json);
  49. _ctx.AddRange(products);
  50. var order = new Order()
  51. {
  52. OrderDate = DateTime.Now,
  53. OrderNumber = "12345",
  54. User = user,
  55. Items = new List<OrderItem>()
  56. {
  57. new OrderItem()
  58. {
  59. Product = products.First(),
  60. Quantity = 5,
  61. UnitPrice = products.First().Price
  62. }
  63. }
  64. };
  65. _ctx.Orders.Add(order);
  66. _ctx.SaveChanges();
  67. }
  68. }
  69. }
  70. }