簡體   English   中英

無法訪問已處置的對象

[英]Cannot access a disposed object

我在測試使用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 我如何使此代碼正常工作。

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的生存期。

由於DataContext在using語句中,因此在上下文超出范圍時,將立即對其調用using (OnlineBankingDataClassesDataContext dbcntx = new OnlineBankingDataClassesDataContext()) 這將導致所有實體分離,並且對該實體上所有需要DataContext的操作都將失敗。 這是在調用account.Balance.ToString()時發生的情況。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM