【发布时间】:2016-03-18 00:17:05
【问题描述】:
我使用代码优先模型进行了此设置:
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 为 null,因此会给出 null 引用异常。 如果有人可以在 LazyLoading 关闭时帮助我访问 IdentityUser 的导航属性,我会很高兴。
谢谢。
【问题讨论】:
-
TestUser和Customer的关系配置完成了吗?
-
这个关系需要什么特殊配置吗?对不起,我不知道有什么,请赐教。
-
复习两件事:1. DbContext 的 OnModelCreating 方法 & 2. LazyLoadingEnabled : asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/…
标签: c# .net entity-framework ef-code-first asp.net-identity