Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rowversion comparison in Entity Framework

How should I compare rowversion fields using Entity Framework? I have one table which has a rowversion column, I want to get data from tables for which the row version is higher than specified value.

byte[] rowversion = ... some value;
 _context.Set<T>().Where(item => item.RowVersion > rowVersion);

This line does not work, it throws the error:

Operator '>' cannot be applied to operands of type 'byte[]' and 'byte[]'

Any idea how I can compare rowversion fields in C#/Entity Framework?

like image 235
bhavesh lad Avatar asked Oct 02 '12 15:10

bhavesh lad


2 Answers

Here is what we did to solve this. Use a compare extension like this:

public static class EntityFrameworkHelper
{
    public static int Compare(this byte[] b1, byte[] b2)
    {
        throw new Exception("This method can only be used in EF LINQ Context");
    }
}

Then you can do this:

byte[] rowversion = .....somevalue;
_context.Set<T>().Where(item => item.RowVersion.Compare(rowversion) > 0);

The reason this works without a C# implementation is because the Compare extension method is never actually called, and EF LINQ simplifies x.Compare(y) > 0 down to x > y.

like image 140
Damon Warren Avatar answered Oct 21 '22 05:10

Damon Warren


Are you sure that is Kosher use of RowVersion ? What happens when it rolls over ?

I think you will need to convert it to string or int first. eg

Encoding.Unicode.GetString(ba)

You can also call SPs from EF. :-)

like image 23
phil soady Avatar answered Oct 21 '22 03:10

phil soady