문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top