Skip to content

Commit d3096ea

Browse files
committed
AspnetRunContextSeed
1 parent 82dae10 commit d3096ea

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

AspNetRunBasic/Entities/Product.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,5 @@ public class Product
1212
[Required, StringLength(255)]
1313
public string Description { get; set; }
1414
public ProductStatus Status { get; set; }
15-
1615
}
1716
}

0 commit comments

Comments
 (0)