首先添加seed

每次应用程序启动,监测一下,是否是第一次启动。如果是第一次执行,我们需要在数据库内添加一个记录

比如说我们的用户账号,我们在第一次进来的时候,我们需要有一个管理员

 

在Data文件夹下新建:

ApplicationDbContextSeed.cs

 

任务50:Identity MVC:DbContextSeed初始化

 

 

 

任务50:Identity MVC:DbContextSeed初始化

 

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("初始默认用户失败!");
                }
            }
        }
    }
}
ApplicationDbContextSeed

相关文章: