Search code examples
c#asp.netasp.net-mvc

Adding new Entity data when user register in ASP.net


    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
 {
     returnUrl ??= Url.Content("~/");
     ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
     if (ModelState.IsValid)
     {
         var user = CreateUser();

         await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
         await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
         var result = await _userManager.CreateAsync(user, Input.Password);

         if (result.Succeeded)
         {
             _logger.LogInformation("User created a new account with password.");
             // add SUPERADMIN role to the user

             await _userManager.AddToRoleAsync(user, "SuperAdmin");

             *var prof = new FakeProfile();
             prof.Name = Input.Name;
             prof.UserId = user.Id;
             prof.User = user;*

I have created a new FakerProfile Entity which user will have by default but user can add new profiles whenever thy want. Here i want to add this info when user first register to the application But i am not able to add that since Identity doesn't have DBContext and I can't seem to find a way for it. How do i do that? How do i access DbContext and add data for another Entity here?

Note: I just want to add new data here because i want to add it during the registration process. I don't want to place this logic on another screen or add this data to the Existing Entities

here is my Context:

public class MyContext : IdentityDbContext<ApplicationUser>
{
    public MyContext (DbContextOptions<MyContext > options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

    public DbSet<FakeProfile> FakeProfile { get; set; }
}

Solution

  • First, make sure you have a constructor in your page model to receive the MyContext.

    public class YourPageModel : PageModel
    {
        private readonly MyContext _context;
    
        public YourPageModel(MyContext context)
        {
            _context = context;
        }
    
        // ... other code
    }
    

    Then, within your OnPostAsync method, you can create a FakeProfile instance and add it to the context.

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl ??= Url.Content("~/");
        ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        if (ModelState.IsValid)
        {
            var user = CreateUser();
    
            await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
            await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
            var result = await _userManager.CreateAsync(user, Input.Password);
    
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");
                // add SUPERADMIN role to the user
    
                await _userManager.AddToRoleAsync(user, "SuperAdmin");
    
                var prof = new FakeProfile();
                prof.Name = Input.Name;
                prof.UserId = user.Id;
                prof.User = user;
    
                _context.FakeProfiles.Add(prof);
                await _context.SaveChangesAsync();
            }
        }
    }