无法访问已处置的对象

时间:2012-07-06 15:38:28

标签: c# linq-to-sql

我在测试使用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有关。我该如何使这段代码正常工作。

2 个答案:

答案 0 :(得分: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的生命周期。

答案 1 :(得分:0)

由于DataContext位于using语句中,using (OnlineBankingDataClassesDataContext dbcntx = new OnlineBankingDataClassesDataContext())  一旦上下文超出范围,就会调用它。这导致所有实体分离,并且需要DataContext的实体上的所有操作都将失败。 这是调用account.Balance.ToString()时发生的情况。

解决此问题的一种方法是创建新的上下文并使用context.Attach(entity)

相关问题