title: EF Relationships and Specification Pattern
body: <p>I've been looking into the specification pattern for my repositories, I'm using EF4 inside my repositories to query the database and map the selected entities by passing in an expression, something like this:-</p>
  
  <pre><code>public IEnumerable&lt;TEntity&gt; Find(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)
  {
      return _objectSet.Where&lt;TEntity&gt;(predicate);
  }
  </code></pre>
  
  <p>This works okay if your just working with the one object set but say if you wanted to select all the comments made by a user that are greater than 128 chars and the user is active. How would you create a specification when two or more object sets are used?</p>
  
  <p>Example:- </p>
  
  <pre><code>class User
  {
      public string Name { get; set; }
      public bool Active { get; set; }
      public virtual ICollection&lt;Post&gt; Posts { get; set; }
  
      public User()
      {
          Posts = new List&lt;Post&gt;();
      }
  }
  
  class Post
  {
      public string Text { get; set; }
      public DateTime Created { get; set; }
      public virtual ICollection&lt;Comment&gt; Comments { get; set; }
  
      public Post()
      {
          Comments = new List&lt;Comment&gt;();
      }
  }
  
  class Comment
  {
      public string Text { get; set; }
      public DateTime Created { get; set; }
  }
  </code></pre>
  
  <p>To do this in Linq is :-</p>
  
  <pre><code>var results = from u in users
                from p in u.Posts
                from c in p.Comments
                where u.Active &amp;&amp; c.Text.Length &gt; 128
                select c;
  </code></pre>
  
  <p>How would you then convert that to a specification class? Maybe I am just not seeing something as it seems like a reasonable thing to do :)</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The specification interface:</p>
  
  <pre><code>public interface ISpecification&lt;TEntity&gt;
  {
      bool IsSatisfiedBy(TEntity entity);
  }
  </code></pre>