首页 > 解决方案 > c#身份无法创建自定义属性

问题描述

这是我从 IdentityUser 派生的类:

    public class User : IdentityUser
{
    public string Extension { get; set; }
}

这是 DbContext

public class SecurityDbContext : IdentityDbContext<User>
{
    private string connectionString;
    private string dbProvider;

    public SecurityDbContext(string connectionString, string dbProvider)
    {
        this.connectionString = connectionString;
        this.dbProvider = dbProvider;
    }

在 Startup.cs

services.AddDbContext<SecurityDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("dataContext")));

        services.AddIdentity<User, IdentityRole>()
        .AddEntityFrameworkStores<SecurityDbContext>()
        .AddSignInManager<SignInManager<User>>()
        .AddDefaultTokenProviders();

我添加了属性扩展,删除了所有表并调用

EnsureDatabasesCreated();

它创建了所有表,但 AspNetUsers 表不包含 Extension 属性。我究竟做错了什么?

标签: c#asp.net-coreasp.net-core-identity

解决方案


您还必须使您的上下文继承自IdentityDbContext<TUser>TUser的自定义用户类型(User在您提供的代码中)也继承自的位置IdentityUser,例如:

public class ApplicationDbContext : IdentityDbContext<User>
{
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
     {
     }
}

这是一个netcore webapp吗?如果是这样,请确保您还在您的身份上注册了身份ServiceProvider并指定了您的自定义用户类,ConfigureServices方法是:

 public void ConfigureServices(IServiceCollection services)
 {
     ...
     services.AddIdentity<User, IdentityRole>()
         .AddEntityFrameworkStores<ApplicationDbContext>()
         .AddSignInManager<SignInManager<User>>()
         .AddUserManager<UserManager<User>>();
     ...
 }

如果需要,指定您的自定义User类和自定义类。Role


推荐阅读