1
public class ApplicationUser : IdentityUser
{
    public ICollection<Profile> Profiles { get; set; }
}

I have a collection of Profiles in ApplicationUser.

I created a custom ProfileService, in method GetProfileDataAsync

var user = await _userManager.GetUserAsync(principal);

user.Profiles returns a null value. It must be somewhere to get the user data before adding to ClaimPrincipals.

How can I customize somewhere in Asp.Net Core Identity to load Profiles when getting User.

In the case of just property, for example, ContractName. It works.

0

2 Answers 2

1

How can I customize somewhere in Asp.Net Core Identity to load Profiles when getting User

Asp.Net Core Identity is abstract system which has no notion of loading related data, which is EF (Core) concept, hence cannot be configured at that level.

EF Core versions prior 5.0 also have no notion of "auto eager load" navigation property (at least not officially). So you must either configure lazy loading (with all associated drawbacks), or issue additional manual eager loading queries as shown in another answer.

EF Core 5.0 provides a way to configure navigation property to be automatically eager loaded using the new Navigation and AutoInclude fluent APIs:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<ApplicationUser>()
        .Navigation(e => e.Profiles)
        .AutoInclude();
}

In EF Core 3.x, although not officially announced and no fluent API available, the same can be configured with SetIsEagerLoaded metadata API:

modelBuilder.Entity<ApplicationUser>()
    .Metadata.FindNavigation(nameof(ApplicationUser.Profiles))
    .SetIsEagerLoaded(true);
1
  • You saved my day. My first approach is made a custom UserStore and override the FindX method. It has a downside that I need to copy the base implementation.
    – Steve Lam
    Nov 21, 2020 at 15:15
0

You need to use Include as follows:

var userId =  User.FindFirstValue(ClaimTypes.NameIdentifier);
_userManager.Users.Where(u => u.Id = userId).Include(u => u.Profiles).FirstOrDefaultAsync();
4
  • I know we need to add Include for Eager Loading, but where I should add?
    – Steve Lam
    Nov 21, 2020 at 11:59
  • @SteveLam You are trying to get the logged-in user info with Profiles collections. Please follow my updated answer. It should work for you. Nov 21, 2020 at 12:01
  • ProfileDataRequestContext has Subject is ClaimPrincipal, it means somewhere before this step, before creating ClaimPrincipal, it gets User data, if we can modify that place, we don't need to write Include in every place we want to get
    – Steve Lam
    Nov 21, 2020 at 12:06
  • Yes! You have to do it. Nov 21, 2020 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.