I have two classes: Property and PropertyValue. A property has several values, where each value is a new revision.
When I get a set of properties, I want to include the latest revision of the value for each property.
in T-SQL, this can be very efficiently done as follows:
SELECT p.Id, pv1.StringValue, pv1.Revision FROM dbo.PropertyValues pv1 LEFT JOIN dbo.PropertyValues pv2 ON pv1.Property_Id = pv2.Property_Id AND pv1.Revision < pv2.Revision JOIN dbo.Properties p ON p.Id = pv1.Property_Id WHERE pv2.Id IS NULL ORDER BY p.Id
The βmagicβ in this query is to concatenate for less than a condition and search for strings without the result called by LEFT JOIN.
How can I accomplish something like this with LINQ to EF?
The best I could come up with was:
from pv in context.PropertyValues group pv by pv.Property into g select g.OrderByDescending(p => p.Revision).FirstOrDefault()
It produces the correct result, but about 10 times slower than the other.
source share