2011-01-23 84 views
0

我有這個類:實體未創建問題

public partial class User 
{ 
    private MyEntities _entities; 

    public User() 
    { 
    } 

    public User(MyEntities entities) 
    { 
     _entities = entities; 
    } 

    public IEnumerable<User> GetUsersRegisteredNewsletter() 
    { 
     return (from u in _entities.Users 
       where u.Subscribe_Newsletter == true 
       select u); 
    } 

    public IEnumerable<CallTimeOption> GetUserCallTimeOptions 
    { 
     get 
     { 
      //_entities = new LighthouseEntities(); 
      // if we uncomment the line above it works  

      var query = from a in _entities.Users.Include("CallTimeOptions") 
         where a.Id == this.Id 
         && a.CallTimeOptions.Any() 
         select a.CallTimeOptions; 

      return query.SelectMany(i => i); 

     } 

    } 
} 

}

現在,當我打電話GetUserCallTimeOptions它拋出一個錯誤

MyEntities _entities = new MyEntities(); 
    User user = new User(_entities); 
    IEnumerable<User> u = user.GetUsersRegisteredNewsletter(); 

    foreach (var a in u) 
    { 

      foreach (var y in user.GetUserCallTimeOptions) 
       Response.Write(y.Text); 
    } 
「不設置到對象的實例對象引用」

但如果我取消註釋GetUserCAllTimeOptions上的這一行,那麼它的工作原理如下:

_entities = new LighthouseEntities(); 

不需要再次創建_entities,不應該這樣工作嗎?

回答

1

您的方法GetUsersRegisteredNewsletter()返回使用默認構造函數創建的用戶實例,該構造函數不初始化_entities。

編輯:一個可能是更好的方式來做到這一切將是用戶內未持有MyEntities實例可言的,也有「使用」的條款創建MyEntities:

using (MyEntities entities = new MyEntities()) { 
    // .... do everything, use only the above declared variable 'entities' 
} 
+0

@sinelaw ,你的意思是刪除「私人MyEntities_entities」;來自用戶類? – user441365 2011-01-23 16:04:08