hrms-api-backend/BMA.EHR.Infrastructure/Persistence/CommandDataSeeder.cs
2023-07-28 15:04:26 +07:00

85 lines
3.3 KiB
C#

using BMA.EHR.Application.Repositories.Commands;
using BMA.EHR.Domain.Models.Commands.Core;
using BMA.EHR.Domain.Models.MetaData;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using OfficeOpenXml;
namespace BMA.EHR.Infrastructure.Persistence
{
public static class CommandDataSeeder
{
public static async Task SeedData(WebApplication app)
{
using var scope = app.Services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<CommandStatusRepository>();
if ((await service.GetAllAsync()).Count() == 0)
{
// read excels into object
var excelFile = "SeedCommand.xlsx";
using (var excel = new ExcelPackage(new FileInfo(excelFile)))
{
var workSheet = excel.Workbook.Worksheets.FirstOrDefault(x => x.Name.ToLower() == "commandstatus");
var totalRows = workSheet?.Dimension.Rows;
int row = 2;
while (row <= totalRows)
{
var cell1 = workSheet?.Cells[row, 1]?.GetValue<string>();
if (cell1 == "" || cell1 == null) break;
var inserted = new CommandStatus
{
Id = Guid.Parse(workSheet?.Cells[row, 1]?.GetValue<string>()!),
Name = workSheet?.Cells[row, 2]?.GetValue<string>()!,
Sequence = (int)workSheet?.Cells[row, 3]?.GetValue<int>()!
};
await service.AddAsync(inserted);
row++;
}
}
}
}
public static async Task SeedCommandType(WebApplication app)
{
using var scope = app.Services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<CommandTypeRepository>();
if ((await service.GetAllAsync()).Count() == 0)
{
// read excels into object
var excelFile = "SeedCommand.xlsx";
using (var excel = new ExcelPackage(new FileInfo(excelFile)))
{
var workSheet = excel.Workbook.Worksheets.FirstOrDefault(x => x.Name.ToLower() == "commandtype");
var totalRows = workSheet?.Dimension.Rows;
int row = 2;
while (row <= totalRows)
{
var cell1 = workSheet?.Cells[row, 1]?.GetValue<string>();
if (cell1 == "" || cell1 == null) break;
var inserted = new CommandType
{
Id = Guid.Parse(workSheet?.Cells[row, 1]?.GetValue<string>()!),
Name = workSheet?.Cells[row, 2]?.GetValue<string>()!,
Category = workSheet?.Cells[row, 3]?.GetValue<string>()!,
CommandCode = workSheet?.Cells[row, 4]?.GetValue<string>()!
};
await service.AddAsync(inserted);
row++;
}
}
}
}
}
}