Search code examples
entity-frameworkconcurrencypocodtooptimistic-concurrency

Entity Framework 5 concurrency update from DTOs


We're using Framework 4.5 and EF 5.0 which shipped with VS 2012. We have an entity that contains a column named RowVersion which I planned to use for concurrency checks. It'a a "Timestamp" value in the MySQL table which updates itself when INSERTing or UPDATEing the record.

Default EF 5 codegen generates this POCO:

Partial Public Class Terminal
    Public Property ID As Long
    Public Property User_ID As Nullable(Of Long)
    Public Property Name As String
    Public Property Number As Nullable(Of Integer)
    Public Property Location As String
    Public Property Description As String
    Public Property IsEnabled As Boolean
    Public Property RowVersion As Date

    Public Overridable Property UserSession As ICollection(Of UserSession) = New        HashSet(Of UserSession)

End Class

I've set concurrency mode of the "RowVersion" property to "fixed" to enable concurrency checks, the "StoreGeneratedPattern" is set to "Computed". We're using DTOs which are mapped via automapper to send data over a WCF service.

We have some problems with updating entities which come back over the service. Here's some code:

Public Sub SaveTerminal(Term As TerminalDto)
    Using db As New PasgaEntities(conString)
        Dim tmpTerminal As Terminal = Mapper.Map(Of Terminal)(Term)

        db.Terminal.Attach(tmpTerminal)

        db.Entry(tmpTerminal).State = EntityState.Modified
        db.SaveChanges() 'throws OptimisticConcurrencyException
    End Using
End Sub

This always ends up in throwing a OptimisticConcurrencyException even though "rowVersion" has not changed. Is this caused by mapping the DTO back to Entity?

Can anybody please point me in the right direction?

Regards


Solution

  • I've solved this using a custom "RowVersion" column which actually is a DateTime field. Since I have to process CRUD manually anyway, it is no problem to update or check this field.