我得到系统.ObjectDisposedException,似乎找不到什么问题
本文关键字:找不到 什么 问题 系统 ObjectDisposedException | 更新日期: 2023-09-27 18:16:07
在第一个add方法中,我得到了异常:ObjectContext实例已被处理,不能再用于需要连接的操作。
我知道我需要在using()括号中,它是,事务是公共虚拟的
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()混淆。