I've run into a case where something that worked fairly well with LINQ to SQL seems to be very obtuse (or maybe impossible) with the Entity Framework. Specifically, I've got an entity that includes a rowversion
property (both for versioning and concurrency control). Something like:
public class Foo
{
[Key]
[MaxLength(50)]
public string FooId { get; set; }
[Timestamp]
[ConcurrencyCheck]
public byte[] Version { get; set; }
}
I would like to be able to take a entity as input, and find all of the other entities that are more recently updated. Something like:
Foo lastFoo = GetSomeFoo();
var recent = MyContext.Foos.Where(f => f.Version > lastFoo.Version);
Now, in the database this would work: two rowversion
values can be compared to one another without any problems. And I've done a similar thing before using LINQ to SQL, which maps the rowversion
to System.Data.Linq.Binary
, which can be compared. (At least to the extent that the expression tree can be mapped back to the database.)
But in Code First, the type of the property must be byte[]
. And two arrays can't be compared with the regular comparison operators. Is there some other way to write the comparison of the arrays that LINQ to Entities will understand? Or to coerce the arrays into other types so that the comparison can get past the compiler?
You can use SqlQuery to write the raw SQL instead of having it generated.
MyContext.Foos.SqlQuery("SELECT * FROM Foos WHERE Version > @ver", new SqlParameter("ver", lastFoo.Version));