【问题标题】:Unable to Add Additional Fields in Aspnetuser table无法在 Aspnetuser 表中添加其他字段
【发布时间】:2020-10-06 06:45:01
【问题描述】:

我创建了一个自定义字段并尝试在 aspnetusers 表中插入自定义字段,但未插入其他字段数据。下面是我试过的代码:

            var identityUser = new CreateUser
            {

                Email = model.Email,
                UserName = model.Email,
                TenantId = obj.ToString(),
                IsAdmin= true


            };
            var result = await _userManager.CreateAsync(identityUser, model.Password);
            var assignRole = await _userManager.AddToRoleAsync(identityUser, "ADMIN");

类:

    public class CreateUser:IdentityUser
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string OrganizationName { get; set; }
    public string Address { get; set; }
    public string Address2 { get; set; }

    public string TenantId { get; set; }
    public bool IsAdmin { get; set; }
}

数据库上下文:

  public class ApplicationDBContext:IdentityDbContext<IdentityUser>
{

    public ApplicationDBContext(DbContextOptions options) : base(options)
    {


    }

}

启动

            //Configure Entity Frameworkcore with SQL Server
        services.AddDbContext<ApplicationDBContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        });

这里有什么遗漏吗,只有原始字段被更新,而添加的字段值没有被插入。

【问题讨论】:

    标签: asp.net-core ef-code-first asp.net-identity


    【解决方案1】:

    这里应该是 CreateUser:

    public class ApplicationDBContext : IdentityDbContext<CreateUser>
    {
    
        public ApplicationDBContext(DbContextOptions options) : base(options)
        {
    
        }
    
    }
    

    Startup.cs:

    services.AddIdentity<CreateUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders()
        .AddDefaultUI();
    

    依赖注入:

    public class HomeController : Controller
    {
        private readonly UserManager<CreateUser> _userManager;
    
        public HomeController(UserManager<CreateUser> userManager)
        {
            _userManager = userManager;
        }
    
        //...
    
    }
    

    自定义的详细步骤可以在Customize the model文档中找到。

    【讨论】:

    • 您应该在启动ConfigureService中将IdentityUser替换为CreateUser,在依赖注入userManager时也使用此CreateUser。
    • 当我更改为此错误时显示:System.InvalidOperationException:无法为“IdentityUser”创建 DbSet,因为该类型未包含在上下文模型中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多