访问从IdentityUser导航属性时LazyLoading已关闭 [英] Accessing Navigation Properties from IdentityUser when LazyLoading is off

查看:234
本文介绍了访问从IdentityUser导航属性时LazyLoading已关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个设置与code第一种模式:

I've this setup with code first model:

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包含客户类的一个实例。

I've extended the IdentityUser to contain an instance of "Customer" Class.

现在考虑这个code:

Now consider this code:

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为空,从而使空引用异常。 我会很高兴,如果有人能帮助我在访问IdentityUser的导航属性时LazyLoading是关闭的。

since lazy loading is off, user.Customer is null and hence gives null reference exception. I'll be glad if anyone can help me in accessing the Navigation Properties of IdentityUser when LazyLoading is off.

感谢。

推荐答案

如果你总是想加载相关数据,而无需使用延迟加载,那么你就需要编写自己的实施 UserStore <的/ code>键,把它插入到你的的UserManager 。例如..

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

然后当你创建你的UserManager,插件本实施 UserStore ,和你的客户数据将被载入与用户..这可能看起来像......

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()))
    {
    }

}

根据您的项目中,的UserManager 实施将是不同的。

这篇关于访问从IdentityUser导航属性时LazyLoading已关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆