-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathDatabaseExtensions.cs
51 lines (43 loc) · 1.55 KB
/
DatabaseExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Ordering.Infrastructure.Data.Extensions;
public static class DatabaseExtensions
{
public static async Task InitialiseDatabaseAsync(this WebApplication app)
{
using var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.MigrateAsync().GetAwaiter().GetResult();
await SeedAsync(context);
}
private static async Task SeedAsync(ApplicationDbContext context)
{
await SeedCustomerAsync(context);
await SeedProductAsync(context);
await SeedOrdersWithItemsAsync(context);
}
private static async Task SeedCustomerAsync(ApplicationDbContext context)
{
if (!await context.Customers.AnyAsync())
{
await context.Customers.AddRangeAsync(InitialData.Customers);
await context.SaveChangesAsync();
}
}
private static async Task SeedProductAsync(ApplicationDbContext context)
{
if (!await context.Products.AnyAsync())
{
await context.Products.AddRangeAsync(InitialData.Products);
await context.SaveChangesAsync();
}
}
private static async Task SeedOrdersWithItemsAsync(ApplicationDbContext context)
{
if (!await context.Orders.AnyAsync())
{
await context.Orders.AddRangeAsync(InitialData.OrdersWithItems);
await context.SaveChangesAsync();
}
}
}