LazyLoading关闭时从IdentityUser访问导航属性



我用代码优先的模型设置了这个:

public class TestContext :IdentityDbContext<TestUser>
{
    public TestContext()
        : base("TestConnection")
    {         
        this.Configuration.LazyLoadingEnabled = false;
    }
    public DbSet<Customer> Customers{get;set;}
}
public class TestUser : IdentityUser
{
    public virtual Customer Customer { get; set; }
}
public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName {get; set;}
}

我已经扩展了IdentityUser以包含"Customer"类的一个实例。

现在考虑这个代码:

var user = UserManager.FindById("some id");                  
if (user != null)
{       
    string str=user.Customer.FirstName; //since lazy loading is off, user.Customer is null and hence gives null reference exception.
}

由于延迟加载已关闭,用户。Customer为null,因此给出null引用异常。如果有人能在LazyLoading关闭时帮助我访问IdentityUser的导航属性,我会很高兴。

谢谢。

如果您总是想在不使用Lazy Loading的情况下加载相关数据,那么您需要编写自己的UserStore实现,并将其插入到UserManager中。例如

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..
    }
}

然后,当您创建UserManager时,插入UserStore的这个实现,您的Customer数据将与用户一起加载。。这可能看起来像。。

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

根据您的项目,UserManager的实现将有所不同。

我已经解决了这个问题:

创建自定义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);
    }
}

替换默认的UserManager服务

配置服务中添加以下内容:

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

更改DI的参数

来自

[FromServices]UserManager<ApplicationUser> userManager

[FromServices]ApplicationUserManager userManager

我希望这能帮助

相关内容

  • 没有找到相关文章