Comparing EF timestamp values
c#, ef-code-first, entity-framework, sql-server
Solution
Yes, you are walking into a trap. The byte array stores a rowversion in big endian format. However, `BitConverter.ToInt64` expects a little endian format on x86 and x64 CPU architectures. I ran a simple test using BitConverter and got an initial rowversion of 0xd207000000000000 and the next rowversion of 0xd307000000000000. SQL Server is incrementing the last byte of the 8-byte sequence, but BitConverter thinks the first byte is most significant. It won't take many increments before your order comparisons stop working once in a while.
The solution is to reverse the order of the rowversion bytes, like this:
BitConverter.ToInt64(item1.Timestamp.Reverse().ToArray(), 0) <
BitConverter.ToInt64(item2.TimeStamp.Reverse().ToArray(), 0)
Problem
I've got an EF Code First model with a byte array field marked with the Timestamp attribute. I need to compare two timestamps with each other and determine which is newer. This seems straightforward but I'm unsure what sort of value SQL Server is filling that byte array with. Do I just convert them to UInt64 values, like so: ``` BitConverter.ToInt64(item1.Timestamp, 0) < BitConverter.ToInt64(item2.TimeStamp, 0) ``` ...or am I walking into some subtle trap here?