我得到System.ObjectDisposedException,似乎无法找到什么是错的
问题描述:
在第一个添加方法我得到的异常: ObjectContext实例已被处置,不能再用于需要连接的操作。我得到System.ObjectDisposedException,似乎无法找到什么是错的
我知道我必须在使用括号(),它是和事务是公共虚拟
public void confirmPayments(List<int> Payments)
{
using (var db = new BankContext())
{
try
{
foreach (int a in Payments)
{
foreach (Payment payment in db.Payment)
{
if (a == payment.Id)
{
Transaction senderTransaction = new Transaction
{
Amount = payment.Amount,
CreationDate = payment.CreationDate,
DueDate = payment.DueDate,
Receiver = payment.Receiver,
Sender = payment.Sender,
KIDMessage = payment.KIDMessage
};
Transaction receiverTranscation = new Transaction
{
Amount = payment.Amount,
CreationDate = payment.CreationDate,
DueDate = payment.DueDate,
Receiver = payment.Receiver,
Sender = payment.Sender,
KIDMessage = payment.KIDMessage
};
Account senderAccount = findAccount(senderTransaction.Sender);
Account receiverAccount = findAccount(receiverTranscation.Receiver);
senderAccount.Transaction.Add(senderTransaction);
senderAccount.Payment.Remove(payment);
senderAccount.Balance = senderAccount.Balance - senderTransaction.Amount;
receiverAccount.Transaction.Add(receiverTranscation);
receiverAccount.Balance = receiverAccount.Balance + receiverTranscation.Amount;
}
}
}
db.SaveChanges();
}
catch (Exception error)
{
System.Diagnostics.Debug.WriteLine("FAILED TO CONFIRM PAYMENT: \n" + error.Message + "\n");
}
}
}
表/类,即时通讯试图加入到(codefirst):
public class Account
{
[Key]
public int Id { get; set; }
public double Balance { get; set; }
public string AccountNumber { get; set; }
public string AccountType { get; set; }
public string CreationDate { get; set; }
public string ClosingDate { get; set; }
public virtual List<Transaction> Transaction { get; set; }
public virtual List<Payment> Payment { get; set; }
}
答
findAccount()也在使用(var db = New BankContext()),我认为这与其他使用confirmPayments()的方法相反。
你正在调用的函数(特别是findAccount)看起来很可疑;你应该可以附加调试器并获取它抛出的实际位置。 – BradleyDotNET
什么是findAccount()?它是否从完全不同的数据库上下文中获取对象并处理该上下文? – David
@大卫谢谢!,这工作..没想到它会因为findAccount()使用()相同的数据库... –