具有多个实体集实例的MVC实体框架状态行为

问题描述:

我想了解EF实体模型(该模型是由实体设计器创建的)的实体集实例之间的关系。基本上我最终得到1个逻辑事务,其中有2个实体的Repository类实例。在一个实例中成功提交数据(通过直接SSMS查询确认到SQLServer)对其他实例不可见。这里的大致流程:具有多个实体集实例的MVC实体框架状态行为

ARepository _aR = new ARepository(); 

A a = _aR.Find(id); //Find does something like: return db.ASet.Where(x => x.id == id); 

b.BeginAcctBal = a.AcctBal; 

brepo.AddTxn(params ... n); //Creates and saves n txns, and creates its own ARepository instance that updates its instance of AcctBal, which I can see happening in the DB) 

A a = _aR.Find(id); //The hope is this gets the updated AcctBal after committed by AddTxn, but it doesn't). 

b.EndAcctBal = a.AcctBal; // Still contains the starting balance value. 

现在,如果我把ARepository _aR = new ARepository();的AddTxn后,则随后的代码确实得到后AddTxn AcctBal值。

问题:

为什么db.ASet.Where(x => x.id == id);没有从DB重装?实际上是否总是从创建_aR实例时的快照中读取?

如果_aR是一个快照,有什么方法可以重新加载它?

如果_aR是快照,如何维护事务完整性?更具体地说,我是否需要做一些事情来维护它,或者EF和MVC 1.0的组合对我来说是否是这种交易魔术?

当您查询ObjectContext(_aR)时,通过默认,它将检查任何已使用相同EntityKey从数据库中检索到的实例。如果它能找到一个,它将返回已经创建的实例,而不是再次返回到数据库。

此行为由ObjectQuery的MergeOption propery确定,默认为MergeOption.AppendOnly。相反,您可能需要使用MergeOption.OverwriteChangesMergeOption.NoTracking,它将每次从DB获取值。

这里有一些引用可能会有所帮助:

  1. Discussion of MergeOptions
  2. Object Context's Refresh Method
  3. Saving Changes and Managing Concurrency (Entity Framework)
  4. Similar forum post