2012-07-18 54 views
0

進出口業務,的ObjectContext的實例已設置,並且不能再被用於需要使用一個單獨的業務邏輯類從數據庫中獲取我的數據對象的連接

public partial class HelperUsers 
{ 
    public User GetUser(string Username, string Password) 
    { 

     using (var myEntities = new BusinessLogic.Entities()) 
     { 
      var query = (from u in myEntities.Users 
         join link in myEntities.linkUserPhoneNumbers on u.UserId equals link.UserId 
         join p in myEntities.PhoneNumbers on link.PhoneNumberId equals p.PhoneNumberId 
         where u.UserName == Username && u.Password == Password 
         select u).ToList(); 



      if (query.Any()) 
       return (User)query[0]; 
     } 
     return null; 

    } 
} 

此使用時效果很好但是我調用頁面上

protected void btnLoad_OnClick(object sender, EventArgs e) 
    { 
     HelperUsers helper = new HelperUsers(); 
     var myUser   helper.GetUser("username", "password") 
     // This works fine 
     lblUserName.Text = myUser.Username 
     // If i try to read one of the child objects from the join it returns an error 
     if (myUser.linkUserPhoneNumbers.Any()) 
     { 
      //do something 
     } 
    } 

我得到的錯誤是

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 

任何硝酸鉀解決這個問題,這樣我就可以訪問我的用戶對象中的所有信息。

回答

2

如果您使用此聲明:

using (var myEntities = new BusinessLogic.Entities()) 

那麼你不能因爲linkUserPhoneNumbers未加載和上下文設置使用myUser.linkUserPhoneNumbers.Any()之後。您需要在查詢中包含linkUserPhoneNumbers或保持上下文不存在。 看這裏:http://msdn.microsoft.com/en-us/library/bb896272.aspx

+0

完美,改變這個屬性讓我讀的兒童對象:) – 2012-07-18 13:21:50

相關問題