Now this is a trick question because you cannot do this:
var a = myDB.Where(p => p.field == "filter").OrderBy("it." + fieldname);
You could change the Where to accept a string, which allows you to change the OrderBy to accept a string, but that's not the question.
How can you turn a string like "productID, productName" in to an OrderBy expression? If I am correct in thinking, maybe the question could be "how to turn a Specification Pattern in to an Expression delegate?"
The problem is I don't know what table they want, and thus I don't know the primary key. I used generics to represent the type of table.
public interface IRepository<E, C> where C : ObjectContext // E is an Entity
{
void Add(E entity);
void Del(E entity);
IList<E> Get(Expression<Func<E, bool>> filterLambda = null, //Where clause
Expression<Func<E, object>> orderbyLambda = null, //OrderBy
int? page = null, //Page to get
int? pageSize = null, //Page Size
Expression<Func<E, object>> selectLambda = null); //Populate Fields
int Count(Expression<Func<E, bool>> filterLambda = null);
bool SaveChanges();
}
The actual statement I use to pull content from the data context (data container?) is
this.GetEntity().Where(filterLambda)
.OrderBy(orderbyLambda)
.Skip(((int)page - 1) * (int)pageSize)
.Take((int)pageSize)
.Select(selectLambda).ToList();
I need the OrderBy()
to implement .Skip()
and .Take()
. For all those of you who think you can do this are correct for Linq to SQL. However, Linq to Entities does not support it:
The method 'Skip' is only supported for sorted input in LINQ to Entities.
The method 'OrderBy' must be called before the method 'Skip'.