hello-shop/samples/MultiTenancySample/MultiTenancySample.FieldIsolationService/EntityFrameworks/DataSeeding.cs

47 lines
1.7 KiB
C#
Raw Normal View History

2024-07-05 11:25:58 +00:00
// Copyright (c) HelloShop Corporation. All rights reserved.
// See the license file in the project root for more information.
using Microsoft.EntityFrameworkCore;
2024-04-28 08:00:15 +00:00
using MultiTenancySample.FieldIsolationService.Entities;
using MultiTenancySample.ServiceDefaults;
namespace MultiTenancySample.FieldIsolationService.EntityFrameworks
{
2024-07-05 11:25:58 +00:00
public class DataSeeding(IDbContextFactory<FieldIsolationServiceDbContext> dbContextFactory, ICurrentTenant currentTenant)
2024-04-28 08:00:15 +00:00
{
public async Task SeedDataAsync()
{
currentTenant.SetTenant("Tenant1");
2024-07-05 11:25:58 +00:00
FieldIsolationServiceDbContext dbContext1 = await dbContextFactory.CreateDbContextAsync();
2024-04-28 08:00:15 +00:00
if (await dbContext1.Database.EnsureCreatedAsync())
{
await dbContext1.AddRangeAsync(new List<Product> {
new() { Id = Guid.NewGuid(), Name = "Product1"},
new() { Id = Guid.NewGuid(), Name = "Product3"},
new() { Id = Guid.NewGuid(), Name = "Product5"}
});
await dbContext1.SaveChangesAsync();
}
currentTenant.SetTenant("Tenant2");
2024-07-05 11:25:58 +00:00
FieldIsolationServiceDbContext dbContext2 = await dbContextFactory.CreateDbContextAsync();
2024-04-28 08:00:15 +00:00
if (await dbContext2.Set<Product>().IgnoreQueryFilters().CountAsync() < 6)
{
await dbContext2.AddRangeAsync(new List<Product>
{
new() { Id = Guid.NewGuid(), Name = "Product2"},
new() { Id = Guid.NewGuid(), Name = "Product4"},
new() { Id = Guid.NewGuid(), Name = "Product6"}
});
await dbContext2.SaveChangesAsync();
}
}
}
}