namespace E.Commerce.Persistence.Data.DataSeed
{
public class DataInitializer
{
private readonly ApplicationDbContext DbContext;
public DataInitializer(ApplicationDbContext dbContext)
{
this.DbContext = dbContext;
}
public async Task InitializerAsync()
{
await SeedData<ProductBrand, int>("brands.json");
await SeedData<ProductType, int>("types.json");
await SeedData<Product, int>("products.json");
await DbContext.SaveChangesAsync();
}
private async Task SeedData<T, TKey>(string fileName) where T : BaseEntity<TKey>
{
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
if (!await DbContext.Set<T>().AnyAsync())
{
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"Data",
"DataSeed",
"JsonFiles",
fileName
);
if (!File.Exists(path)) throw new FileNotFoundException($"Seed file not found: {path}");
var data = await File.ReadAllTextAsync(path);
var list = JsonSerializer.Deserialize<List<T>>(data, options);
if (list?.Count > 0)
{
await DbContext.Set<T>().AddRangeAsync(list);
}}
} }
}
namespace E.Commerce.Persistence.Data.DataSeed
{
public class DataInitializer
{
private readonly ApplicationDbContext DbContext;
public DataInitializer(ApplicationDbContext dbContext)
{
this.DbContext = dbContext;
}
public async Task InitializerAsync()
{
await SeedData<ProductBrand, int>("brands.json");
await SeedData<ProductType, int>("types.json");
await SeedData<Product, int>("products.json");
await DbContext.SaveChangesAsync();
}
private async Task SeedData<T, TKey>(string fileName) where T : BaseEntity<TKey>
{
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
if (!await DbContext.Set<T>().AnyAsync())
{
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"Data",
"DataSeed",
"JsonFiles",
fileName
);
if (!File.Exists(path)) throw new FileNotFoundException($"Seed file not found: {path}");
var data = await File.ReadAllTextAsync(path);
var list = JsonSerializer.Deserialize<List<T>>(data, options);
if (list?.Count > 0)
{
await DbContext.Set<T>().AddRangeAsync(list);
}}
} }
}