我有這個設置與代碼第一種模式:從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