1

I wonder if this is possible

var table = _db.GetTable<T>(); var data = table.Where(t => !t.Deleted).OrderBy("Name"); 

I cannot do t.Name as t only have Id and Deleted

The base class which contains this method looks like this

public class RepositoryBase<T> where T : class, Interfaces.IModel 

IModel only knows of Deleted and Id

Regards

2
  • Why is there no t.Name, if the table has a Name column to order by? Commented Aug 5, 2009 at 8:25
  • ITs a base class that public class RepositoryBase<T> where T : class, Interfaces.IModel The interface only contains Deleted and Id as all the tables have that Commented Aug 5, 2009 at 8:31

2 Answers 2

2

It the underlying type doesn't have an obvious Name member, this I can't see how this would work.

If the problem is simpy that you only know the column to order by at runtime; then to order by a dynamic property you need to build an Expression on the fly. Here's some old code I have that does this, and should support "Name" and things like "Customer.Name" (child properties); I haven't tested it recently, though:

public static class OrderExtensions { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderBy"); } public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "OrderByDescending"); } public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenBy"); } public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property) { return ApplyOrder<T>(source, property, "ThenByDescending"); } static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) { ParameterExpression arg = Expression.Parameter(typeof(T), "x"); Expression expr = arg; foreach(string prop in property.Split('.')) { // use reflection (not ComponentModel) to mirror LINQ expr = Expression.PropertyOrField(expr, prop); } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), expr.Type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); return (IOrderedQueryable<T>) typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments( ).Length ==2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), expr.Type) .Invoke(null, new object[] {source, lambda}); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

I think you need to create a specific repository for this entity since your abstraction model doesn't fit for this case. Something like:

public class MyEntityRepository : RepositoryBase<MyEntity> 

Comments