-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathDatabaseExtentions.cs
46 lines (37 loc) · 1.48 KB
/
DatabaseExtentions.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
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Ordering.Infrastructure.Data.Extensions;
public static class DatabaseExtentions
{
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()) return;
await context.Customers.AddRangeAsync(InitialData.Customers);
await context.SaveChangesAsync();
}
private static async Task SeedProductAsync(ApplicationDbContext context)
{
if (await context.Products.AnyAsync()) return;
await context.Products.AddRangeAsync(InitialData.Products);
await context.SaveChangesAsync();
}
private static async Task SeedOrdersWithItemsAsync(ApplicationDbContext context)
{
if (await context.Orders.AnyAsync()) return;
await context.Orders.AddRangeAsync(InitialData.OrdersWithItems);
await context.SaveChangesAsync();
}
}