我有这个设置与代码第一种模式:从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包含“客户”类的一个实例。
现在考虑下面的代码:
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为空,因此给空引用异常。 如果有人能够帮助我在LazyLoading关闭时访问IdentityUser的导航属性,我会很高兴。
谢谢。
配置是TestUser的和客户之间的关系呢? – jd4u 2014-10-13 13:37:06
我们是否需要这种关系的特殊配置?我很抱歉,但我不知道任何,请赐教。 – 2014-10-14 02:32:21
回顾两件事:1.DbContext的OnModelCreating方法&2. LazyLoadingEnabled:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with- the-entity-framework-in-an-asp-net-mvc-application – jd4u 2014-10-14 11:39:09