1

我一直在尋找網絡,但我還沒有找到任何關於此的信息。正如我們所知,Linq在運行之前爲我們提供了將表達式轉換爲T-SQL的CompiledQuery。我試圖設計一個通用的存儲庫來與我的EF進行交互,但是除了Linq查詢被編譯。如果任何人都可以指點一下,這將是偉大的:)使用通用存儲庫設計模式編譯Linq

+0

http://linqautocompiler.codeplex.com/可能工作作爲入口點 – gliljas 2011-05-04 14:04:16

回答

2

這幾乎是不可能的,因爲如果你想預編譯查詢你必須知道它。對於通用存儲庫,通常只有這樣:

public interface IRepository<T> 
{ 
    IQueryable<T> GetQuery(); 
} 

所以使用存儲庫實例的代碼負責定義查詢。預編譯,需要具體的庫將包含類似的方法:

IEnumerable<Order> GetOrdersWithHeaderAndItemsByDate(DateTime date, int take, int skip); 
IEnumerable<OrderHeader> GetOrderHeadersOrderedByCustomer(int take, int skip); 

很明顯,你很難在準備通用存儲庫這樣的查詢怎麼一回事,因爲它們依賴於具體的實體。

2

您正在尋找的實施Specification pattern。基本上,這是創建一個包含篩選查詢所需信息的Specification對象。通過使用規範,您可以實現Generic Repository實現,並將自定義查詢邏輯放入規範中。該規範的基類看起來類似:

public class Specification<TEntity> 
{ 
    public Specification(Expression<Func<TEntity, bool>> predicate) 
    { 
     _predicate = predicate; 
    } 

    public bool IsSatisfiedBy(TEntity entity) 
    { 
     return _predicate.Compile().Invoke(entity); 
    } 

    public Expression<Func<TEntity,bool>> PredicateExpression{ 
     get{ return _predicate; } 
    }  

    private Expression<Func<TEntity, bool>> _predicate; 
} 

關於實現與實體框架的規範模式非常有幫助的物品可以在http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/找到