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

Ami*_*tal 5 .net c# 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;}
}
Run Code Online (Sandbox Code Playgroud)

我已将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.
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Exc*_*ted 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..
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

根据您的项目,UserManager实施将有所不同.