在Asp.net Core (Abp)添加种子数据SeedData

Asp.net core添加种子数据

添加文件夹SeedData
添加静态类SeedData

public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new AsdfContext(
            serviceProvider.GetRequiredService<DbContextOptions<AsdfContext>>())) {
            if (context.Users.Any())
            {
                return;
            }
            context.Users.AddRange(
            new User
            {
                FirstName = "user1",
                LastName = "user1",
                UserName = "user1",
                Email = "[email protected]",
                Password = "user1"
            },
            new User
            {
                FirstName = "user2",
                LastName = "user2",
                UserName = "user2",
                Email = "[email protected]",
                Password = "user2"
            }
            );
        context.SaveChanges();
    }
}
}

在Program.cs中添加静态类初始化方法

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            SeedData.Initialize(services);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred seeding the DB.");
        }
    }
    host.Run();
    CreateHostBuilder(args).Build().Run();
}

更新数据库,启动程序生成初始化数据。

Abp添加种子数据

在EntityFrameworkCore新建Players文件夹,新建类DefaultPlayerBuilder

public class DefaultPlayerBuilder
{
    private readonly AprilDbContext _context;
    public DefaultPlayerBuilder(AprilDbContext context)
    {
        _context = context;
    }

    public void Create()
    {
        CreatePlayers();
    }
    private void CreatePlayers()
    {
        // Default tenant

        var defaultPlayers = _context.Players.Any();
        if (defaultPlayers)
        {
        return;
        }
        _context.Players.AddRange(
        new Player("模板LCD—1", "公共板块", "000187D22411223_121627", true),
        new Player("模板LCD—2", "公共板块", "000187D22411223_121627", true)
        );
        _context.SaveChanges();
    }
}

在EntityFrameworkCore的SeedHelper.cs中添加对应的生成器

public static void SeedHostDb(AprilDbContext context)
{
    context.SuppressAutoSetTenantId = true;

    // Host seed
    new InitialHostDbBuilder(context).Create();

    // Default tenant seed (in host database).
    new DefaultTenantBuilder(context).Create();
    new TenantRoleAndUserBuilder(context, 1).Create();
     new DefaultPlayerBuilder(context).Create();
}

更新数据库后,启动后台程序,可以看到
在Asp.net Core (Abp)添加种子数据SeedData_第1张图片

你可能感兴趣的:(在Asp.net Core (Abp)添加种子数据SeedData)