2009-08-05 3 views
1

이 가능한 경우 궁금linq2SQL +있는 OrderBy 문자열 값

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

톤은 아이디 및 삭제

이 방법이

처럼 보이는이 포함 된 기본 클래스를 가지고 내가 t.Name 할 수 없습니다
public class RepositoryBase<T> where T : class, Interfaces.IModel 

IModel 해당 단지 삭제 및 아이디

감사합니다 알고

+0

테이블에 이름 열이있는 경우 왜 t.Name이 없습니까? – Blorgbeard

+0

의 공용 클래스는 T RepositoryBase하는 기본 클래스 : 클래스, Interfaces.IModel 이 인터페이스는 모든 테이블이 그 –

답변

2

기본 유형이 이 아니며이 분명 함 Name 회원입니다. 이것이 어떻게 작동하는지 알 수 없습니다.

문제가 simpy 인 경우 런타임시 주문할 열만 알면됩니다. 동적 속성으로 주문하려면 즉시 Expression을 작성해야합니다. 다음은이 작업을 수행하는 일부 오래된 코드입니다. "Name"과 "Customer.Name"(자식 속성)과 같은 것을 지원해야합니다. 그래도 최근에 그것을 테스트하지 않은 :

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}); 
    } 
} 
+0

+1 우수 가지고 삭제 및 ID를 포함합니다을! 정확히 내가 필요한 것. :) – magnus

0

당신이이 경우에 적합하지 않는 추상화 모델부터이 엔티티에 대한 특정 저장소를 만들 필요가 있다고 생각합니다. 다음과 같음 :

public class MyEntityRepository : RepositoryBase<MyEntity>