I’m trying to extend ApplicationUser with custom properties on a fresh Blazor server project. Here’s what I have:
public class Tariff
{
public int Id { get; set; }
public required string Name { get; set; }
public double MonthlyFee { get; set; }
public int NetworkSpeed { get; set; }
}
public class ApplicationUser : IdentityUser
{
// Added field and foreignkey attribute after, but that changed nothing
public int TariffId { get; set; }
[ForeignKey(nameof(TariffId))]
public required Tariff Tariff { get; set; }
public double Balance { get; set; }
}
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options)
{
public DbSet<Tariff> Tariff { get; set; }
}
After applying generated migration, I got a Tariff
table with corresponding columns and a TariffId
column in AspNetUsers
table.
I’ve also modified registration process to be as following:
var user = Activator.CreateInstance<ApplicationUser>();
var defaultTariff = DbContext.Tariff.FirstOrDefault();
user.Tariff = defaultTariff!;
return user;
And manually populated Tariff table with example rows. After that, I’m trying to access the field in a Blazor page.
@page "/Account/Personal"
@using Microsoft.AspNetCore.Identity
@using WebApp.Components.Account.Shared
@using WebApp.Data
@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ApplicationDbContext DbContext
<InputSelect id="tariff" @bind-Value=user.Tariff>
@foreach (var tariff in DbContext.Tariff.ToList())
{
<option value="@tariff">@tariff.Name</option>
}
</InputSelect>
@code {
private ApplicationUser user = default!;
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
user = await UserAccessor.GetRequiredUserAsync(HttpContext);
}
}
But debugger shows that Tariff field is null. However other fields – i.e. TariffId and Balance are populated normally.
What am I missing for auto-filling this property?