Search code examples
asp.net-coreasp.net-identity

Reference an additional UserSettings class through the ApplicationUser class


I'm trying to add a reference to an additional table, and then load the information from the database. I want to add UserSettings as a user can have multiple settings that can be configured.

I think that I have set up everything correctly, but somehow the information from the foreign-key table is not loaded. I tried various posts from previous questions, but I'm unable to resolve the issue.

The code in UserSetting.cs

public class UserSetting
{                                                     
    public string ID { get; set; }
    public string SettingType { get; set; }
    public string Description { get; set; }
    public string SettingValue { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

The code in ApplicationUser.cs

public class ApplicationUser : IdentityUser
{ 
    public virtual List<UserSetting> UserSettings { get; set; }
}

The code in AppDbContext.cs

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {                    
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUser>(b =>          
        {                                        
              b.HasMany(e => e.UserSettings) 
                    .WithOne()             
                    .HasForeignKey(uc => uc.ID) 
                    .IsRequired();                       
        });                                                
     }
}

The code in HomeController.cs

public class HomeController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;
    public HomeController(UserManager<ApplicationUser> userManager
    {
         this.userManager = userManager;
    }

    public async Task<IActionResult> LoadProfile()     
    {
         var user = await userManager.FindByNameAsync("username");
    }
}

Where and how do I load the UserSettings into the ApplicationUser class so that I can reference it?


Solution

  • You could query the related data using Include() like below:

    public async Task<IActionResult> LoadProfile()
    {
            var user = await userManager.Users
                     .Include(u=>u.UserSettings)
                     .SingleAsync(u=>u.UserName=="[email protected]");
    }
    

    If you want to use FindByEmailAsync() to get the related data, you could refer to this thread to create your own IUserStore where you load related data in the FindByEmailAsync method.