简体   繁体   中英

asp.net core identity custom user data with a collection

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM