2009-02-10 15 views
6

Ho una domanda del tipo:Entity Framework clausola WHERE dinamica

var function = GetSomeExpression();  

using (FooModel context = new FooModel()) 
{ 
    var bar = context.Bar.Where(function); 
} 

mi piacerebbe fare un metodo generico che può eseguire Dove contro diversi Enti nel contesto. L'obiettivo non è avere a che fare context.Bar.Where, context.Car.Where, Context.Far.Where, ecc

Qualcosa che non può essere fatto, ma illustra l'obiettivo è:

var q = context.GetObjectContext(T).Where(queryFunction); 

Ho cercato di utilizzare Relfection e posso ottenere il metodo Where, ma non so come eseguirlo rispetto al contesto che passa nel delegato. Ho anche guardato DynamicMethod, ma fare l'intera cosa di IL non mi piace.

Quello che ho finora:

private List<T> GetResults<T>(Expression<Func<T, bool>> queryFunction) 
{ 
    // note: first() is for prototype, should compare param type 
    MethodInfo whereMethod = typeof(Queryable).GetMethods() 
     .Where(m => m.Name == "Where") 
     .First().MakeGenericMethod(typeof(T)); 

    // invoke the method and return the results 
    List<T> result = whereMethod.Invoke(
    // have the method info 
    // have the expression 
    // can reference the context 
    ); 

    throw new NotImplementedException(); 
} 

Questo è possibile fare?

+0

avevo provato a fare di questo un po 'indietro e finito per la costruzione di un deposito per ciascuno di essi. Mi piacerebbe sapere cosa pensano gli altri. Il designer.cs genera una ctx.CreateQuery ("[Bar]"); – bendewey

risposta

7

Questo è il modo più facile poi quello che stavo cercando prima:

private List<T> GetResults<T>(IQueryable<T> source, 
    Expression<Func<T, bool>> queryFunction) 
{ 
    return source.Where(queryFunction).ToList<T>(); 
}