I can order entities using properties:
context.MySet.OrderBy( entity => entity.Id);
But here I've to know that PK is only one column named 'Id'.
I'need generic way of ordering.
context.Set<TEntity>().OrderByPk()
Thus I can guarantee that client always receives entities in the same order.
I could create the sequence of OrderBy()
and ThenBy()
but both these methods expect generic Expression<Func<TEntity,TKey>>
. But if I work with generic Type I do not know the type of Keys until run time.
I've created function to get epressions for ordering, but I do not know how to 'attach' them to the query.
public IEnumerable<Expression> GetKeys<TDbEntity>() where TDbEntity : class
{
var keyMembers = (this as IObjectContextAdapter).ObjectContext.MetadataWorkspace.GetItem<EntityType>(typeof(TDbEntity).FullName, true, DataSpace.OSpace).KeyMembers;
foreach (var keyMember in keyMembers)
{
var parameter = Expression.Parameter(typeof (TDbEntity));
var expression = Expression.Lambda(Expression.Property(parameter, keyMember.Name), parameter);
yield return expression;
}
}