通过webhost扩展方式初始化EFCore数据库
Posted 明明.如月
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过webhost扩展方式初始化EFCore数据库相关的知识,希望对你有一定的参考价值。
通过webhost扩展方式初始化EFCore数据库
1.定义WebHostMigrationExtensions类
public static class WebHostMigrationExtensions
{
public static IWebHost MigrationDbContext<TContext>(this IWebHost host,
Action<TContext, IServiceProvider> seeder) where TContext : DbContext
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var logger = services.GetRequiredService<ILogger<TContext>>();
var context = services.GetService<TContext>();
try
{
context.Database.Migrate();
seeder(context, services);
logger.LogInformation($"执行DbContext{typeof(TContext).Name} seed执行成功!");
}
catch (Exception ex)
{
logger.LogError(ex, $"执行DbContext{typeof(TContext).Name} seed执行失败!");
}
}
return host;
}
}
public class ApplicationContextSeed
{
private UserManager<User> _userManager;
public async Task SeedAsync(ApplicationDbContext context,IServiceProvider service)
{
if (!context.Users.Any())
{
_userManager = service.GetRequiredService<UserManager<User>>();
var defaultUser = new User
{
UserName = "[email protected]",
Email = "[email protected]",
NormalizedEmail= "[email protected]",
NormalizedUserName = "admin"
};
var result = await _userManager.CreateAsync(defaultUser, "pwd123456");
if (!result.Succeeded)
{
throw new Exception("初始化数据库失败");
}
}
}
}
2.在buildWebHost中调用
public static void Main(string[] args)
{
BuildWebHost(args)
.MigrationDbContext<ApplicationDbContext>((context, services) =>
{
new ApplicationDbContextSeed().SeedAsync(context, services).Wait();
})
.Run();
}
以上是关于通过webhost扩展方式初始化EFCore数据库的主要内容,如果未能解决你的问题,请参考以下文章