.net core Identity web 项目创建(二)之手动创建和 自定义 扩展 IdentityUser IdentityRole
上一篇是 框架自动创建 Identity 项目 这一篇是 手动创建
创建 web 应用


Nuget 下载
Microsoft.AspNetCore.Identity.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
新建 AppliactionDBContext 类
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace TestIdentity1.Data
{
public class AppliactionDBContext : IdentityDbContext
{
public AppliactionDBContext(DbContextOptions<AppliactionDBContext> options) : base(options)
{
}
}
}
appsettings.json 文件 的数据库连接
"ConnectionStrings": {
"DefaultConnection": "Server=192.168.0.196;Database=TestIdentity1;uid=root;pwd=123456"
}
Program.cs 配置 数据库配置 和 identity 配置
string defaultConnection = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppliactionDBContext>(options =>
{
options.UseMySql(defaultConnection, new MySqlServerVersion(new Version(8, 0, 27)));
});
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppliactionDBContext>();
生成迁移文件
add-Migration init -outputdir data -context AppliactionDBContext
生成数据库
updata-database
生成 数据库成功

IdentityUser 基类 的属性

IdentityRole 基类属性

现在现有的属性不够用 需要 自定义 IdentityUser IdentityRole 扩展增加属性
新建两个类 AppliactionUser AppliactionRole 各自继承 IdentityUser IdentityRole
/// <summary>
/// 扩展用户
/// </summary>
public class AppliactionUser:IdentityUser
{
/// <summary>
/// 用户所在城市
/// </summary>
public string City { get; set; }
}
/// <summary>
/// 扩展 角色
/// </summary>
public class AppliactionRole:IdentityRole
{
/// <summary>
/// 角色别名
/// </summary>
public string NickName { get; set; }
}
修改 AppliactionDBContext 为 IdentityDbContext<AppliactionUser, AppliactionRole, string>
/// <summary>
/// 扩展用户 和 角色
/// </summary>
public class AppliactionDBContext : IdentityDbContext<AppliactionUser, AppliactionRole, string>
{
public AppliactionDBContext(DbContextOptions<AppliactionDBContext> options) : base(options)
{
}
}
修改
builder.Services.AddIdentity<AppliactionUser, AppliactionRole>()
.AddEntityFrameworkStores<AppliactionDBContext>();

生成数据库迁移文件
add-migration extend_user_role
生成数据库
update-database
查看数据库 是否 增加两个属性


浙公网安备 33010602011771号