using Fengling.AuthService.Models; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace Fengling.AuthService.Data; public static class SeedData { public static async Task Initialize(IServiceProvider serviceProvider) { using var scope = serviceProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); var userManager = scope.ServiceProvider.GetRequiredService>(); var roleManager = scope.ServiceProvider.GetRequiredService>(); context.Database.EnsureCreated(); var adminRole = await roleManager.FindByNameAsync("Admin"); if (adminRole == null) { adminRole = new ApplicationRole { Name = "Admin", Description = "System administrator", CreatedTime = DateTime.UtcNow }; await roleManager.CreateAsync(adminRole); } var adminUser = await userManager.FindByNameAsync("admin"); if (adminUser == null) { adminUser = new ApplicationUser { UserName = "admin", Email = "admin@fengling.local", RealName = "系统管理员", Phone = "13800138000", TenantId = 1, EmailConfirmed = true, IsDeleted = false, CreatedTime = DateTime.UtcNow }; var result = await userManager.CreateAsync(adminUser, "Admin@123"); if (result.Succeeded) { await userManager.AddToRoleAsync(adminUser, "Admin"); } } var testUser = await userManager.FindByNameAsync("testuser"); if (testUser == null) { testUser = new ApplicationUser { UserName = "testuser", Email = "test@fengling.local", RealName = "测试用户", Phone = "13900139000", TenantId = 1, EmailConfirmed = true, IsDeleted = false, CreatedTime = DateTime.UtcNow }; var result = await userManager.CreateAsync(testUser, "Test@123"); if (result.Succeeded) { var userRole = new ApplicationRole { Name = "User", Description = "普通用户", CreatedTime = DateTime.UtcNow }; await roleManager.CreateAsync(userRole); await userManager.AddToRoleAsync(testUser, "User"); } } } }