2

客戶有很多ReservationRequests,ReservationRequest只有一個Customer。Linq with Entity Framework渴望加載

比方說,我找回像這樣

var c = dataContext.ReservationRequestSet.FirstOrDefault(i => i.id == RequestId); 

我ReservationRequest我讓我的ReservationRequest沒有問題,但是當我做這樣的事情。

 if (c != null) 
     { 
      int id = c.Customers.id; 

我得到一個

Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. 

Source Error: 

Line 75:    if (c != null) 
Line 76:    { 
Line 77:     int id = c.Customers.id; 

我有EF經驗非常少,但這種類型的東西NHibernate的工作沒有問題,我失去了一個環境某處EF?

感謝 吉姆

+0

您使用的是哪個版本的實體框架?最新支持延遲加載,就像你期望的那樣,否則你必須編寫一些額外的代碼。 – 2010-11-01 19:34:37

+0

有沒有簡單的方法來檢查? – jim 2010-11-02 03:24:11

+0

我建議您在「客戶」中更改ReservationRequestSet「客戶」的導航屬性。它更可變。 – 2010-11-11 11:38:05

回答

5

你必須明確地渴望負荷Customers導航屬性上ReservationRequestSet

var c = dataContext.ReservationRequestSet.Include("Customers") 
             .FirstOrDefault(i => i.id == RequestId); 

隨着.NET 4,EF在默認情況下執行延遲加載,但因爲你正在開發一個web應用程序我建議關閉它,並始終使用Eager Loading,因爲它可能想要在關閉對象上下文時嘗試執行延遲加載,因此會導致異常,這是Web和WCF應用程序中非常典型的場景。

+0

你是男人。 – jim 2010-11-01 19:39:30

+0

沒問題的夥計:) – 2010-11-01 20:03:28

1

如果您使用實體框架V1,你必須明確地加載孩子們喜歡的(你找回實體加載後):(當你檢索實體到急於負載)

if(!c.CustomersReference.IsLoaded) 
    c.CustomersReference.Load(); 

或者:

var c = dataContext.ReservationRequestSet 
        .Include("Customers") 
        .FirstOrDefault(i => i.id == RequestId); 

如果您使用實體框架v4的,你可以嘗試使用新的延遲加載功能:

using(YourContext db = new YourContext()) 
{ 
    db.ContextOptions.LazyLoadingEnabled = true; 
    // query here 
} 

如果你走這條路,你根本不用擔心顯式加載導航屬性。