简体   繁体   中英

Is there a way of preventing EF6 from reverting a property on an entity post Save?

I am using CodeFirst and EF6 with individual mappings for states.

I have a weird scenario that is as follows:

  1. Create a new till entity ( state is 'Added' ).
  2. Assign a closing value to the new till, ie '99.01m' .
  3. Save it to DB (till saved successfully).
  4. Create a new order object
  5. Create order items object/s
  6. Update till closing values to reflect successful order, ie '101.01m'.
  7. Save the order object to DB ( state is 'added' and saved successfully ).
  8. After save, inspect closing value.
  9. Observe till closing values, expected 101.01 is actually 99.01m

If I explicitly mark the till:

Cache.TodaysCashDraw.ObjectState = ObjectState.Unchanged;

The value is reverted regardless of applying an object state or not.

Cache.TodaysCashDraw.ObjectState = ObjectState.Modified;

However if I mark it as modified then 99.01m is committed into the DB.

So basically whatever changes appear on my till object are getting reverted, now this is fine but i would like an explanation as to why? Ideally I would like to the changes on my till object to be persisted and not reverted as shown above. As the till is going to change numerous times during the working day so I would like to commit changes for a till only when necessary. Orders and Items should get saved straight away but the Till Object in memory just needs to reflect the orders that have been processed against it. That's my current thinking and approach which worked well in EF4 and DB First.

Does anybody know what's going on here and what is the ideal way of solving this problem?

A lame backup plan is to commit the till changes straight away.

One way would be in a disconnected scenario is to detach the entity in question:

            // detach the till to prevent it from being tracked.
            Cache.TodaysCashDraw.ObjectState = ObjectState.Detached;

Then when you need to save its state, just re-attach it:

           _ctx.Context.Set<CashDrawsMony>().Attach(_till);

This solves my problem completely.

On a more humerous note, I was actually looking at the Attach method, wondering what it was for? = )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM