[英]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.