• 50-Identity MVC:DbContextSeed初始化


    1-创建一个可以启动时如果没有一个账号刚创建1个新的账号

    namespace MvcCookieAuthSample.Data
    {
        public class ApplicationDbContextSeed
        {
            public async Task SeedAsync(ApplicationDbContext context, IServiceProvider service)
            {
                if (!context.Users.Any())
                {
                    var _userManager= service.GetRequiredService<UserManager<ApplicationUser>>();
                    var user = new ApplicationUser() {
                         Email="qinzhb@163.com",
                         UserName="qinzhb",
                         NormalizedUserName="qinzhb"
                    };
    
                    var result = await _userManager.CreateAsync(user, "123456@Byd");
                    if (!result.Succeeded)
                    {
                        throw new Exception("初始化用户失败");
                    }
    
                }
            }
        }
    }

    2-增加一个扩展方法,用于启动时初始化数据库

    namespace MvcCookieAuthSample
    {
        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 service = scope.ServiceProvider;
                    var logger = service.GetRequiredService<ILogger<TContext>>();
                    var context =  service.GetService<TContext>();
    
                    try
                    {
                        context.Database.Migrate();
                        seeder(context, service);
                        logger.LogInformation("执行方法数据库初始化成功");
    
                    }
                    catch
                    {
                        logger.LogError("执行数据库数据库初始化密码失败");
                    }
    
                }
                
                return host;
            }
        }
    }

    3-把上面的2方法增加到启动类中

      public static void Main(string[] args)
            {
                CreateWebHostBuilder(args)
                    
                    .Build()
                    .MigrationDbContext<ApplicationDbContext>((context,services)=> {
                        new Data.ApplicationDbContextSeed().SeedAsync(context, services).Wait();
                    }).Run();
            }
  • 相关阅读:
    [NOI2019]回家路线(最短路,斜率优化)
    LOJ6686 Stupid GCD(数论,欧拉函数,杜教筛)
    Codeforces Global Round 4 题解
    CF908G New Year and Original Order(DP,数位 DP)
    [BJOI2019]光线(DP)
    CF1194F Crossword Expert(数论,组合数学)
    SPOJ31428 FIBONOMIAL(斐波那契数列)
    Codeforces Round 573 (Div.1) 题解
    [THUPC2018]弗雷兹的玩具商店(线段树,背包)
    数学基础
  • 原文地址:https://www.cnblogs.com/qinzb/p/9458105.html
Copyright © 2020-2023  润新知