简体   繁体   中英

how to handle concurrency in EF4(ORACLE)

I would like to know how to safely update data when programming with Entity Framework 4(ODAC).

void DescreaseInventory(int id, int qty){
  var order = (from o in context.Orders where o.ID ==id select o).FirstOrDefault;
  if( order != null ){
    if( ((Order)order).Qty < qty )
      throw new ApplicationException( "Not Enough Inventory!!" );
    else
      ((Order)order).Qty -= qty;
  }
  else{
  //...some code...
  }
  //will content.savechange
}

This code will be dangerous(evade the qty checking) once race condition happens. Who knows how to do this correctly?

EDIT : Now I know EF4 provide a mechanism to make a column as a tracking token. But I'm not sure how can I create this kind of column in oracle DB(9i)? what's the proper column type?

By using optimistic concurrency = either rowversion or timestamp column in the database. Those columns are maintained by database and it automatically change their value when record is updated. If you correctly configures your EF model to use such column for concurrency checking you will avoid some problems.

When one process takes your order it will load its current timestamp and when it tries to save the record the timestamp will be part of the Where condition for update. If the order was changes by another process in the mean time it will not find a record to update and throws exception. You will have to handle such exception by refreshing data from database to get actual state and actual timestamp and for example by recomputing qty or passing it for resolution to user.

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