开发者

Compiled Linq with Generic Repository Design Pattern

开发者 https://www.devze.com 2023-02-16 23:01 出处:网络
I\'ve been looking开发者_JS百科 around the web but I\'ve yet to found any information on this.As we know Linq gives us CompiledQuery which transform the expression into T-SQL before running it. I\'m t

I've been looking开发者_JS百科 around the web but I've yet to found any information on this. As we know Linq gives us CompiledQuery which transform the expression into T-SQL before running it. I'm trying to design a generic repository to interact with my EF but with the exception the Linq queries is compiled. If anyone could shead some light on this that would be great :)


It is hardly possible because if you want to pre-compile query you must know it. With generic repository you usually have only this:

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

So the code using a repository instance is responsible for defining the query. Pre-compilation requires concrete repository which will contain methods like:

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

etc.

Obviously you can hardly prepare such queries in generic repository beacuse they are dependent on concrete entity.


You are looking for an implementation of the Specification pattern. Basically, this is creating a Specification object that contains the information needed to filter your query. By using Specifications, you can have a Generic Repository implementation, and put your custom query logic in the specification. The specification base class looks something like:

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;
} 

A very helpful article about implementing the specification pattern with the Entity Framework can be found at http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/

0

精彩评论

暂无评论...
验证码 换一张
取 消