From 74078ede9e1d22c174fddd42f89cc57999a227a0 Mon Sep 17 00:00:00 2001 From: Charles Showalter Date: Tue, 10 May 2022 09:07:07 -0700 Subject: [PATCH] Added Seed Data --- Infrastructure/Data/StoreContextSeed.cs | 57 +++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Infrastructure/Data/StoreContextSeed.cs diff --git a/Infrastructure/Data/StoreContextSeed.cs b/Infrastructure/Data/StoreContextSeed.cs new file mode 100644 index 0000000..de4c058 --- /dev/null +++ b/Infrastructure/Data/StoreContextSeed.cs @@ -0,0 +1,57 @@ +using System.Text.Json; +using Core.Entities; +using Infrastructure.Data; +using Microsoft.Extensions.Logging; + +namespace Infrastructure +{ + public class StoreContextSeed + { + public static async Task SeedAsync(StoreContext context, ILoggerFactory loggerFactory) + { + try + { + if (!context.ProductBrands.Any()) + { + var brandsData = File.ReadAllText("../Infrastructure/Data/SeedData/brands.json"); + var brands = JsonSerializer.Deserialize>(brandsData); + foreach (var item in brands) + { + context.ProductBrands.Add(item); + } + + await context.SaveChangesAsync(); + } + + if (!context.ProductTypes.Any()) + { + var typesData = File.ReadAllText("../Infrastructure/Data/SeedData/types.json"); + var types = JsonSerializer.Deserialize>(typesData); + foreach (var item in types) + { + context.ProductTypes.Add(item); + } + + await context.SaveChangesAsync(); + } + + if (!context.Products.Any()) + { + var productsData = File.ReadAllText("../Infrastructure/Data/SeedData/products.json"); + var products = JsonSerializer.Deserialize>(productsData); + foreach (var item in products) + { + context.Products.Add(item); + } + + await context.SaveChangesAsync(); + } + } + catch (Exception ex) + { + var logger = loggerFactory.CreateLogger(); + logger.LogError(ex.Message); + } + } + } +} \ No newline at end of file