OptimisticConcurrencyException Issue RRS feed

  • Question

  • I got an issue regarding OptimisticConcurrencyException in Entity FrameWork.

    I have a table named 'Optimist' with following fields in the database

    1. Id(Primary Key)
    2. Name
    3. Age and I followed Database First Strategy.

    I tried executing the following code with all the Scalar Properties set to

    Concurrency Mode-->'Fixed',

    Now at the point where execution control arrives at "MessageBox.Show("Wait")",

    I opened SQLServer and updated the 'age' field of the same record to

    a different value, I got the OptimisticConcurrencyException and I handled it properly.

    But if the table has multiple records with the same name (i.e., 'Jack') and following

    the same procedure as above, it is not yielding any Exception and

    moreover by default it is taking as 'ClientWins'.

    container = new CoddsDataEntities(); // 'CoddsDataEntities' is a my Entity Container var rec = container.Optimists.Where(i => i.name == "Jack"); try { MessageBox.Show("wait"); foreach (var i in rec) //when 'rec' has multiple records i used this foreach { //loop.When 'rec' is having single record replace i.age = 25 //this foreach loop with "rec.age = 25" and also } //used the

    //"var rec = container.Optimists.Where(i => i.name == "Jack").First();" container.SaveChanges(); } catch (OptimisticConcurrencyException ex) { MessageBox.Show("Exception occurred"); container.Refresh(System.Data.Objects.RefreshMode.ClientWins, rec); container.SaveChanges(); }

    So my question is,why is it having a different behavior with 'rec' having a single record

    and with multiple records.

    • Edited by jack_dv Saturday, May 4, 2013 8:04 AM
    • Moved by Bob Shen Monday, May 6, 2013 7:48 AM
    Saturday, May 4, 2013 7:57 AM


  • Hi Jack,

    In fact there are some differences using "container.Optimists.Where(i => i.name == "Jack");"  and  "container.Optimists.Where(i => i.name == "Jack").First();".

    It is lazy loading using the first statement, means that a query to database will be executed when it is used. So the query is executed at foreach (var I in rec) statement, which happens after you modified the database and everything works fine.

    However, if you are using First() extension method, a query like "SELECT TOP(1) ..." will be executed to database immediately. So it happens before you modified the database and there is the exception.

    Best regards,

    Chester Hong
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Chester Hong Monday, May 13, 2013 8:54 PM
    Tuesday, May 7, 2013 8:06 AM