views:

75

answers:

1

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 instance. 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?

Thx.

A: 

Hi Dale,

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:

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