![](/img/trans.png)
[英]How to handle System.InvalidOperationException in entity framework?
[英]Entity Framework System.InvalidOperationException
我在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`
我不想修改我的類結構,在這種情況下我可以正確使用Entity Framework嗎? 怎么樣?
謝謝你的回答。
您正在混合多個數據上下文: account
附加到databaseContainer
( databaseContainer.Transactions.AddObject(transaction);
account
作為來自transaction
的嵌套屬性)但來自Model1Container container = new Model1Container();
。
您不能同時在多個上下文中使用實體實例。
我也看到了數據容器的某種單例模式,這通常是一個壞的,壞的,壞主意......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.