|
| 1 | +using AspNetRunBasic.Entities; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace AspNetRunBasic.Data |
| 9 | +{ |
| 10 | + public class AspnetRunContextSeed |
| 11 | + { |
| 12 | + public static async Task SeedAsync(AspnetRunContext aspnetrunContext, ILoggerFactory loggerFactory, int? retry = 0) |
| 13 | + { |
| 14 | + int retryForAvailability = retry.Value; |
| 15 | + |
| 16 | + try |
| 17 | + { |
| 18 | + // TODO: Only run this if using a real database |
| 19 | + // aspnetrunContext.Database.Migrate(); |
| 20 | + // aspnetrunContext.Database.EnsureCreated(); |
| 21 | + |
| 22 | + if (!aspnetrunContext.Products.Any()) |
| 23 | + { |
| 24 | + aspnetrunContext.Products.AddRange(GetPreconfiguredProducts()); |
| 25 | + await aspnetrunContext.SaveChangesAsync(); |
| 26 | + } |
| 27 | + } |
| 28 | + catch (Exception exception) |
| 29 | + { |
| 30 | + if (retryForAvailability < 10) |
| 31 | + { |
| 32 | + retryForAvailability++; |
| 33 | + var log = loggerFactory.CreateLogger<AspnetRunContextSeed>(); |
| 34 | + log.LogError(exception.Message); |
| 35 | + await SeedAsync(aspnetrunContext, loggerFactory, retryForAvailability); |
| 36 | + } |
| 37 | + throw; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private static IEnumerable<Product> GetPreconfiguredProducts() |
| 42 | + { |
| 43 | + return new List<Product>() |
| 44 | + { |
| 45 | + new Product() { Name = "IPhone X", Description = "IPhone X Well Done", Status = ProductStatus.InStock }, |
| 46 | + new Product() { Name = "Samsung 10", Description = "Samsung X Well Done", Status = ProductStatus.InStock }, |
| 47 | + new Product() { Name = "Huawei Plus", Description = "Huawei X Well Done", Status = ProductStatus.InStock } |
| 48 | + }; |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments