我在 2 个不同的类中使用实体框架容器。
private static DataManager instance;
private Model1Container databaseContainer;
private DataManager()
{
databaseContainer = new Model1Container();
}
public static IDataManager Instance
{
get
{
if (instance == null)
{
instance = new DataManager();
}
return instance;
}
}
public void OpenNewAccount(int amount)
{
Account account = new Account();
Transaction transaction = new Transaction();
transaction.Account = account;
transaction.Amount = amount;
transaction.Date = DateTime.Now;
if (TransactionExecutor.Instance.ExecuteTransaction(transaction, account))
{
//EXCEPTION An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll
//Additional information: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
databaseContainer.Transactions.AddObject(transaction);
databaseContainer.Accounts.AddObject(account);
databaseContainer.SaveChanges();
}
}
class AccountStateTransactionValidator : AbstractTransactionValidator
{
override
public bool HandleTransaction(Transaction transaction, Account account)
{
if (account.AccountState == null || (account.Amount < account.AccountState.LeftBound || account.Amount >= account.AccountState.RightBound))
{
Model1Container container = new Model1Container();
AccountState properState = (from st in container.AccountStates
where st.LeftBound <= account.Amount &&
st.RightBound >= account.Amount
select st).FirstOrDefault();
if (properState != null)
{
account.AccountState = properState;
}
else
{
return false;
}
}
return base.nextTransaction(transaction, account);
}
}
我得到了这个例外:
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()</ExceptionString></Exception></TraceRecord>
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.Entity.dll`
我不想修改我的类结构,在这种情况下我可以正确使用实体框架吗?如何?
感谢您的回答。