码迷,mamicode.com
首页 > 数据库 > 详细

通过webhost扩展方式初始化EFCore数据库

时间:2018-08-28 14:12:54      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:targe   ihe   ams   action   relative   []   ons   mat   container   

通过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 = "Luna@qq.com",
                    Email = "Luna@qq.com",
                    NormalizedEmail= "Luna@qq.com",
                    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数据库

标签:targe   ihe   ams   action   relative   []   ons   mat   container   

原文地址:https://www.cnblogs.com/mmry/p/9547657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!