Search code examples
asp.net-coreef-code-firstasp.net-identity

Unable to Add Additional Fields in Aspnetuser table


I have created a custom fields and trying to insert the custom fields in aspnetusers tables, but the additional fiels data is not inserted. Below is the code i tried:

            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");

Class:

    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; }
}

DbContext:

  public class ApplicationDBContext:IdentityDbContext<IdentityUser>
{

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


    }

}

StartUp

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

Is anything missing here, only the original fields gets updated while the added fields value is not inserted.


Solution

  • Here should be the CreateUser:

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

    Startup.cs:

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

    Dependency injection:

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

    The detail steps to customize could be found in Customize the model document .