2012-07-06 166 views
0

我現在面臨一個問題,在測試其使用LINQ to SQL被測試如下無法訪問

方法(簡單的)的DAL庫已釋放的對象:

public List<tblAccount> GetAccountsByCustomer(tblCustomer customer) 
{ 
    using (OnlineBankingDataClassesDataContext dbcntx = new OnlineBankingDataClassesDataContext()) 
    { 
     var accounts = dbcntx.tblAccounts.Where(p => p.tblCustomer.ID.CompareTo(customer.ID)==0); 
     return accounts.ToList<tblAccount>(); 
    } 
} 

測試代碼如下所示:

static tblCustomer GetTopOneCustomer() 
{ 
    OnlineBankingDataClassesDataContext dbcntx = new OnlineBankingDataClassesDataContext(); 
    var customers = dbcntx.tblCustomers.Take(1); 
    return customers.Single<tblCustomer>(); 
} 

public static void Should_List_All_Account_By_Customer() 
{ 

    tblCustomer customer = GetTopOneCustomer(); 

    DataController dc = new DataController(); 
    List<tblAccount> accounts=dc.GetAccountsByCustomer(customer); 
    foreach (tblAccount account in accounts) 
    { 
     string accountdetails=string.Format("Account ID:{0} \n Account Type:{1} \n Balance:{2} \n BranchName:{3} \n AccountNumber:{4}", 
         account.ID.ToString(), account.tblAccountType.Name, 
         account.Balance.ToString(), 
         account.tblBranch.Name, account.Number); 

     Console.WriteLine(accountdetails); 

    } 
} 

我收到錯誤「無法訪問已處理的對象」。當訪問像這種情況下的關聯對象時,我使用的是account.tblAccountType.Name。我知道這與DataContext有關。我該如何獲得這個代碼的工作。

回答

1

dbcntx是一次性物品。垃圾收集器可以在GetTopOneCustomer()被調用並處理後隨時來。這看起來正在發生。

嘗試改變GetTopOneCustomer()到:

static tblCustomer GetTopOneCustomer(OnlineBankingDataClassesDataContext dataContext) 
{ 
    //Stuff 
} 

內。然後Should_List_All_Account_By_Customer()改變它像這樣:

using (OnlineBankingDataClassesDataContext dataContext = new OnlineBankingDataClassesDataContext()) 
{ 
    tblCustomer customer = GetTopOneCustomer(dataContext); 
    //More Stuff 
} 

這樣你控制dataContext的壽命。

+0

我通常會將它們包裝在一個類中,因此當該類處於活動狀態時,您的數據庫連接將處於活動狀態。 – Trisped 2012-07-06 15:53:40

+0

@DaveShaw問題是,在處理dbcntx DataContext後,實體正在訪問相關對象。 GetTopOneCustomer根本不應該引起任何問題。 – JonC 2012-07-06 16:07:45

0

由於DataContext處於using語句中,因此只要上下文超出範圍,Dispose就會立即調用。這導致所有實體都被分離,並且需要DataContext的實體上的所有操作都將失敗。 這是account.Balance.ToString()被調用時發生的情況。

解決此問題的一種方法是創建一個新的上下文並使用context.Attach(entity)

+0

其中是'DataContext'所在的using語句? – Trisped 2012-07-06 15:52:35

+0

在GetAccountsByCustomer中。 – JonC 2012-07-06 15:58:00

+0

啊,沒有足夠的滾動。 – Trisped 2012-07-06 20:39:38