88 lines
3.0 KiB
C#
88 lines
3.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Newtonsoft.Json;
|
|
using TodoAPI2.Models;
|
|
using TTSW.EF;
|
|
using TTSW.Utils;
|
|
|
|
namespace TestAPI01.Seed
|
|
{
|
|
public class SeedData
|
|
{
|
|
private const string ApplicationDbContextSeedDirPath = @"Seed\ApplicationDbContextSeed\";
|
|
|
|
public static void EnsureSeedData(IServiceProvider serviceProvider, bool enableSeedApplicationDb)
|
|
{
|
|
Console.WriteLine("Seeding database...");
|
|
|
|
using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
|
|
{
|
|
var context = scope.ServiceProvider.GetService<DataContext>();
|
|
context.Database.Migrate();
|
|
|
|
var ApplicationDbContextSeedDirPath = Path.Combine("Seed", "ApplicationDbContextSeed");
|
|
|
|
if (enableSeedApplicationDb)
|
|
{
|
|
|
|
|
|
// if (!context.master_legal_entity.Any())
|
|
// {
|
|
// using (StreamReader file = System.IO.File.OpenText(GetAbsolutePath(Path.Combine(ApplicationDbContextSeedDirPath, @"Legal_entity.json"))))
|
|
// {
|
|
// JsonSerializer serializer = new JsonSerializer();
|
|
// var list = (List<MASTER_Legal_entityEntity>)serializer.Deserialize(file, typeof(List<MASTER_Legal_entityEntity>));
|
|
// foreach (var i in list) FillData(i);
|
|
// context.AddRange(list);
|
|
// context.SaveChanges();
|
|
// }
|
|
// }
|
|
// else
|
|
// Console.WriteLine("Legal_entity have already been imported to db.");
|
|
|
|
}
|
|
}
|
|
|
|
Console.WriteLine("Done seeding database.");
|
|
Console.WriteLine();
|
|
}
|
|
|
|
public static void FillData(BaseEntity<Guid> i)
|
|
{
|
|
i.id = Guid.NewGuid();
|
|
i.isActive = true;
|
|
i.created = DateTime.Now;
|
|
i.updated = DateTime.Now;
|
|
}
|
|
|
|
public static string GetAbsolutePath(string filePath)
|
|
{
|
|
var currentDir = Directory.GetCurrentDirectory();
|
|
return Path.Combine(currentDir, filePath);
|
|
}
|
|
}
|
|
|
|
public class MigrationData
|
|
{
|
|
public static void EnsureMigration(IServiceProvider serviceProvider)
|
|
{
|
|
Console.WriteLine("Migrate database...");
|
|
|
|
using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
|
|
{
|
|
var context = scope.ServiceProvider.GetService<DataContext>();
|
|
context.Database.Migrate();
|
|
}
|
|
|
|
Console.WriteLine("Done.");
|
|
Console.WriteLine();
|
|
}
|
|
}
|
|
}
|