Accessing Navigation Properties from IdentityUser when LazyLoading is off

后端 未结 2 1909
暗喜
暗喜 2021-01-13 06:43

I\'ve this setup with code first model:

public class TestContext :IdentityDbContext
{
    public TestContext()
        : base(\"TestConnectio         


        
相关标签:
2条回答
  • 2021-01-13 07:25

    I have solved with this:

    Create a custom UserManager

    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger, IHttpContextAccessor contextAccessor) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, contextAccessor) { }
    
        public override Task<ApplicationUser> FindByIdAsync(string userId)
        {
            return Users.Include(c => c.Esercizio).FirstOrDefaultAsync(u => u.Id == userId);
        }
    }
    

    Replace default UserManager service

    In your ConfigureServices add this:

    services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders().AddUserManager<ApplicationUserManager>();
    

    Change arguments for DI

    from

    [FromServices]UserManager<ApplicationUser> userManager
    

    to

    [FromServices]ApplicationUserManager userManager
    

    I hope this helps

    0 讨论(0)
  • 2021-01-13 07:41

    If you are always wanting to load the related data without using Lazy Loading then you will need to write your own implementation of the UserStore and plug that into your UserManager. For example..

    public class ApplicationUserStore : UserStore<TestUser>
    {
        public ApplicationUserStore(TestContext context) : base(context)
        {
        }
    
        public override TestUser FindByIdAsync(string userId)
        {
            return Users.Include(c => c.Customer).FirstOrDefault(u => u.Id == userId);
            //you may want to chain in some other .Include()s like Roles, Claims, Logins etc..
        }
    }
    

    then when you create your UserManager, plugin this implementation of the UserStore, and your Customer data will be loaded with the user.. this may look something like..

    public class TestUserManager : UserManager<TestUser>
    {
        public TestUserManager() : base(new ApplicationUserStore(new TestContext()))
        {
        }
    
    }
    

    depending on your project, the UserManager implementation will be different.

    0 讨论(0)
提交回复
热议问题