2009-08-05 19 views
1

これが可能である場合、私は疑問に思うlinq2SQL + [並べ替え基準文字列値

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

トンはIDのみ、削除

このメソッドは、この

のように見えるが含ま基本クラスを持っているように、私はt.Nameを行うことはできません
public class RepositoryBase<T> where T : class, Interfaces.IModel 

IModelをしか

削除し、Idのよろしく

0123を知っています
+0

注文する名前列がテーブルにある場合、なぜt.Nameはありませんか? – Blorgbeard

+0

ITは パブリッククラスはT RepositoryBaseことを基本クラス:すべてのテーブルが優秀なこと –

答えて

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持っているように、クラス、Interfaces.IModel インターフェイスが削除のみとIDが含まれています!正確に私が必要なもの。 :) – magnus

0

を私はあなたがあなたの抽象化モデルが、この場合には向いていないので、このエンティティの特定のリポジトリを作成する必要があると思います。次のようなものがあります。

public class MyEntityRepository : RepositoryBase<MyEntity> 
関連する問題