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

时间:2014-10-12 11:15:33

标签: c# .net entity-framework ef-code-first asp.net-identity

我使用代码优先模型进行此设置:

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扩展为包含&#34; Customer&#34;的实例。类。

现在考虑以下代码:

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

由于延迟加载已关闭,user.Customer为null,因此提供空引用异常。 当LazyLoading关闭时,如果有人可以帮助我访问IdentityUser的导航属性,我会很高兴。

感谢。

2 个答案:

答案 0 :(得分:8)

如果您总是希望在不使用延迟加载的情况下加载相关数据,则需要编写自己的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实施方式会有所不同。

答案 1 :(得分:4)

我已经解决了这个问题:

创建自定义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服务

ConfigureServices 中添加以下内容:

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

更改DI的参数

[FromServices]UserManager<ApplicationUser> userManager

[FromServices]ApplicationUserManager userManager

我希望这会有所帮助