无法访问已处置的对象 [英] Cannot access a disposed object
问题描述
在测试使用LINQ to SQL的DAL库时,我遇到了一个问题
i'm facing a issue while testing the DAL Library which uses LINQ to SQL
正在测试的方法如下(一个简单的方法):
Method that is being Tested as below (a simple one):
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
有关.我应该如何使此代码正常工作.
I'm getting an error "Cannot access a disposed object." when accessing associated object like in this case, I'm using account.tblAccountType.Name
. I know it has something to do with DataContext
. How shall I get this code working.
推荐答案
dbcntx
是一次性对象.调用GetTopOneCustomer()
后,垃圾收集器可以随时出现并进行处理.看起来正在发生什么.
dbcntx
is a disposable object. The Garbage Collector can come along at any time after GetTopOneCustomer()
has been called and dispose of it. Which is what looks like is happening.
尝试将GetTopOneCustomer()
更改为:
static tblCustomer GetTopOneCustomer(OnlineBankingDataClassesDataContext dataContext)
{
//Stuff
}
然后在Should_List_All_Account_By_Customer()
内部将其更改为:
Then inside Should_List_All_Account_By_Customer()
change it like so:
using (OnlineBankingDataClassesDataContext dataContext = new OnlineBankingDataClassesDataContext())
{
tblCustomer customer = GetTopOneCustomer(dataContext);
//More Stuff
}
这样,您可以控制dataContext
的生存期.
This way you control the lifetime of the dataContext
.
这篇关于无法访问已处置的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!