views:

45

answers:

2

I need to page records but I don't know the Entity's fields. Any way to OrderBy the Key (whatever it is) or simply specify some default OrderBy Lambda?

For example, I can do this with the Where Clause without knowing the Entity's properties:

 var myRecords = DC.Products.Where( p => p);

This is a case where the Skip and Take require an OrderBy, but I don't know the Entity's Key fields.

EDIT:

When I don't have OrderBy() when using Skip().Take(), I get this error:

The method 'Skip' is only supported for sorted input in LINQ to Entities.
The method 'OrderBy' must be called before the method 'Skip'.
+1  A: 

For getting the Key property name, you would have to leverage the MetadataWorkspace object. Once you get the name from it, you can build a dynamic query with EntitySQL to get the results or using the Query Builder methods to build an EntitySQL for you, like I showed below, they are just like LINQ to Entities methods except that they accept string instead of Lambdas:

var keyName = context
    .MetadataWorkspace
    .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace)
    .BaseEntitySets.First(meta => meta.ElementType.Name == "Product")
    .ElementType.KeyMembers.Select(k => k.Name).FirstOrDefault();

    var query = context.Products.OrderBy("it." + keyName);
    var anotherQuery = context.Products.Where("it." + keyName + " = 1" );
Morteza Manavi
That is very promising and impressive. My difficulty is one cannot use the string syntax after a previous lambda expression. The .Where(p => p...) removes the ability to extend with the OrderBy using strings. I would need to use .Where("it. something").OrderBy("it." + keyName); It's no so difficult except that my interface only includes lambda expressions, so I would need to somehow convert the lambda expression to string.
Dr. Zim
You can always add LINQ methods to an ObjectQuery or to query builder methods, but the only query builder method that you can add to a LINQ expression is Include. For example this is possible: .Where("it...").Where(p => p...) but not the other way around. In your case, when you want to build dynamic queries, I would write the whole query in EntitySQL as it's a perfect situation for leveraging ESQL.
Morteza Manavi
A: 

If you didn't need any order do this:

myList.OrderBy(o=>1==1).Take(10)

but if order is important define an interface with just one property (name it ID), and implement this interface in all of your items, and do orderby on ID

SaeedAlg
"Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context." The OrderBy accepted the 1==1 but then gave that error.
Dr. Zim