MVC Entity Framework state behavior with multiple instances of an entityset
I'm trying to understand the relationship between entityset instances of an EF Entities model (the model was created by Entity Designer). Basically I end up with 1 logical transaction having 2 instances of an entity's Repository class. Data committed successfully (confirmed by direct SSMS query to SQLServer) in one instance does not become visible to the other ins开发者_开发知识库tance. Here's roughly the flow:
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.
Now if I put ARepository _aR = new ARepository();
immediately after the AddTxn, then the subsequent code does indeed get the post-AddTxn AcctBal value.
Questions:
Why does db.ASet.Where(x => x.id == id);
not reload from the db? Is it really always reading from a snapshot from when the _aR instance is created?
If _aR is a snapshot, is there any way to reload it?
If _aR is a snapshot, how is transactional integrity being maintained? More specifically, do I need to do something to maintain it, or does the combination of EF and MVC 1.0 do this transactional magic for me?
When you query your ObjectContext (_aR), by default, it will check for any instances that have already been retrieved from the DB with the same EntityKey. If it can find one, it will return the already created instance, rather than going back to the DB again.
This behavior is determined by the ObjectQuery's MergeOption propery, which defaults to MergeOption.AppendOnly. Instead, you may want to use MergeOption.OverwriteChanges or MergeOption.NoTracking, which will get the values from the DB everytime.
Here are some references which may be helpful:
- Discussion of MergeOptions
- Object Context's Refresh Method
- Saving Changes and Managing Concurrency (Entity Framework)
- Similar forum post
精彩评论