• Asp.Net Core EF Migrations(二)


      asp.net core 中实现DBContext的初始化,先创建一个ApplicationDBContextSeed,作为初始化基础数据的类,

    需要引用 using Microsoft.Extensions.DependencyInjection 和 using Microsoft.Extensions.Logging ,只有在初始化创建数据库的时候将默认的admin账号写入表中

     public class ApplicationDBContextSeed
        {
            private UserManager<ApplicationUser> _userManager;
            public  async Task SeedAsync(ApplicationDBContext contest,IServiceProvider serviceProvider)
            {
                if (!contest.Users.Any())
                {
                    _userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    
                    var defultUser = new ApplicationUser
                    {
                        UserName = "admin",
                        Email = "leo@qq.com",
                        NormalizedUserName = "admin"
                    };
                    var  resilt= await _userManager.CreateAsync(defultUser, "123456");
                    if(!resilt.Succeeded)
                    {
                        throw new Exception("初始化用户信息失败!");
                    }
                }
            }
        }
    创建WebHostMirgationExtensions
     public static class WebHostMirgationExtensions
        {
            public  static IWebHost  MigrateDbContext<TContext>(this IWebHost host,Action<TContext,IServiceProvider> sedder) 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();//每次执行都会自动去更新数据库
                        sedder(context, services);
                        logger.LogInformation($"执行DBContext:{typeof(TContext).Name} seed方法成功");
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"执行DBContext:{typeof(TContext).Name} seed方法失败");
                    }
                }
               
                return host;
            }
        }

    修改Program

      

     public static void Main(string[] args)
            {
                BuildWebHost(args)
                    .MigrateDbContext<ApplicationDBContext>((context, server) => {
                        new ApplicationDBContextSeed().SeedAsync(context, server).Wait(); }
                    ).Run();
            }
  • 相关阅读:
    常用的几个vagrant命令
    window下sh文件在linux转码
    centos 7 免密登录
    centos7系列-给普通用户sudo权限
    Hadoop hdfs完全分布式搭建教程
    ribbon的注解使用报错--No instances available for [IP]
    修改VirtualBox虚拟机默认存储路径及虚拟机迁移方法
    【SpringMVC】文件上传Expected MultipartHttpServletRequest: is a MultipartResolver错误解决
    发现不错待研究的技术
    android的开发 华为手机上不显示menu键
  • 原文地址:https://www.cnblogs.com/li-lun/p/8745298.html
Copyright © 2020-2023  润新知