0

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;
    }
}
Pavel Voronin
  • 11,811
  • 6
  • 54
  • 113
  • These posts were helpful: http://stackoverflow.com/questions/41244/dynamic-linq-orderby-on-ienumerablet http://stackoverflow.com/questions/2841585/create-linq-to-entities-orderby-expression-on-the-fly http://stackoverflow.com/questions/12564545/set-key-inside-order-by-clause-in-linq-dynamically – Pavel Voronin Aug 12 '13 at 11:25

1 Answers1

0

This Jon's answer was very helpful.

Then I can return only strings for key properties and call OrederByProperty and ThenByProperty

Community
  • 1
  • 1
Pavel Voronin
  • 11,811
  • 6
  • 54
  • 113