-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathPostgreSqlSeeder.cs
56 lines (46 loc) · 2.09 KB
/
PostgreSqlSeeder.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
52
53
54
55
56
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Steeltoe.Samples.PostgreSqlEFCore.Data;
using Steeltoe.Samples.PostgreSqlEFCore.Entities;
namespace Steeltoe.Samples.PostgreSqlEFCore;
internal sealed class PostgreSqlSeeder
{
public static async Task CreateSampleDataAsync(IServiceProvider serviceProvider)
{
await using AsyncServiceScope scope = serviceProvider.CreateAsyncScope();
await using var appDbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DropCreateTablesAsync(appDbContext);
await InsertSampleDataAsync(appDbContext);
}
private static async Task DropCreateTablesAsync(DbContext dbContext)
{
bool wasCreated = await dbContext.Database.EnsureCreatedAsync();
if (!wasCreated)
{
// The database already existed. Because apps usually don't have permission to drop the database,
// we drop and recreate all the tables in the DbContext instead.
var databaseCreator = (RelationalDatabaseCreator)dbContext.Database.GetService<IDatabaseCreator>();
await DropTablesAsync(dbContext);
await databaseCreator.CreateTablesAsync();
}
}
private static async Task DropTablesAsync(DbContext dbContext)
{
IEnumerable<string> tableNames = dbContext.Model.GetEntityTypes().Select(type => type.GetSchemaQualifiedTableName()!);
IEnumerable<string> dropStatements = tableNames.Select(tableName => "DROP TABLE IF EXISTS \"" + tableName + "\";");
string sqlStatement = string.Join(Environment.NewLine, dropStatements);
await dbContext.Database.ExecuteSqlRawAsync(sqlStatement);
}
private static async Task InsertSampleDataAsync(AppDbContext appDbContext)
{
appDbContext.SampleEntities.AddRange(new SampleEntity
{
Text = "Test Data 1 - AppDbContext"
}, new SampleEntity
{
Text = "Test Data 2 - AppDbContext"
});
await appDbContext.SaveChangesAsync();
}
}