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?

Answers


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.


Need Your Help

Replace the Visual Studio Find Results

c# .net visual-studio-2010 visual-studio visual-studio-addins

I'm wanting to create a replacement window which displays the Find results (and maybe also Find Symbol Results in the future).

PyQt5 without QtGui and QtWidgets

python pyqt pyqt5

I am trying to build pyqt5 for my virtualenv but there is no QtWidgets package or module or whatever it should be. And I can't import QtGui.