How to maintain concurrency in Entity framework? RRS feed

  • Question

  • In my online exam project there are 4 methods in WCF:

    1)GetSections--------------------Select only sections
    2)GetExamDetails-----------------Select exam details from db
    3)GetQuestionsAndInsert----------Select questions and insert in Exam table
    4)UpdateAttempt<small>------------------Update attempts in db

    These methods are executed when user click on exam link. When 2 or more users click on that link exam page get load successfully but if 2 users click on same link at same time then any one of then or both get error from above any 1 method. Errors like transaction failed,can not 'read' data while other transaction is running etc.
    I used Entity Framework in my project. I know it is concurrency issue but I am not able to resolve it. Please tell me how to manage this problem. 
    • Edited by MNamrata Wednesday, May 7, 2014 6:15 AM
    Wednesday, May 7, 2014 6:00 AM


  • The simple thing to do is add a date/timestamp column to the record. When you add a new record or update the record, you take the current date and time and update the column.

    Now when doing an update, you have to get the record to update it. So when you get the record for update, you hold on to the record's primary-key and the date/time from the date/timestamp column.

    You update the record in memory. But before you try to save the record, you take the held on to record-id and the date/timestamp and try to retrieve the record by the criteria of record-id and date/timestamp.

    If you cannot retrieve the record by its record-id and timestamp, then you know that another user has updated the record and changed the timestamp, before the user could save their changes to the same record. You must stop the save and notify the user that the record was changed by another user.

    It's the simple thing to do on a concurrency check.

    Wednesday, May 7, 2014 9:50 AM