任务50:Identity MVC:DbContextSeed初始化
任务50:Identity MVC:DbContextSeed初始化
首先添加seed
每次应用程序启动,监测一下,是否是第一次启动。如果是第一次执行,我们需要在数据库内添加一个记录
比如说我们的用户账号,我们在第一次进来的时候,我们需要有一个管理员
在Data文件夹下新建:
ApplicationDbContextSeed.cs


using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using MvcCookieAuthSample.Models; using Microsoft.Extensions.DependencyInjection; namespace MvcCookieAuthSample.Data { public class ApplicationDbContextSeed { private UserManager<ApplicationUser> _userManager; public async Task SeedAsync(ApplicationDbContext context,IServiceProvider services) { if (context.Users.Any()) { _userManager = services.GetRequiredService<UserManager<ApplicationUser>>(); var defaultUser = new ApplicationUser { UserName = "Administrator", Email = "haogeili@163..com", NormalizedEmail="admin" }; var result=await _userManager.CreateAsync(defaultUser, "Password$123"); if (!result.Succeeded) { throw new Exception("初始默认用户失败!"); } } } } }
调用Seed方法
WebHostMigrationExtensions.cs
这里扩展的方法,我们要扩展的是IWebHost


这里我们要把依赖注入引入进来



包装器我们在哪里使用呢?Program.cs程序启动文件里面

这样我们的初始化就完成了。

.MigrationDbContext<ApplicationDbContext>((context,services)=> { new ApplicationDbContextSeed().SeedAsync(context, services) .Wait(); })
运行测试
先把我们本地的数据库删掉。然后再运行我们的程序

更正代码

看到我们执行成功的输出信息

默认已经初始化的 用户信息

纠正代码错误:

重新运行并新建数据库

登陆成功。!!!!!

浙公网安备 33010602011771号