title: Writing dynamic LINQ queries as closure methods
body: <p>I'm trying to write a C# repository with atomic contexts and feel like this is a perfect situation for the usage of a closure, but I can't quite grok how to get it done in C#. I have this as a main method in my repository:</p>
  
  <pre><code>...
      protected virtual IQueryable&lt;T&gt; AsQueryable()
      {
          return _context.ObjectSet&lt;T&gt;().AsQueryable();
      }
  ...
  </code></pre>
  
  <p>Meanwhile, I have derived classes with methods like:</p>
  
  <pre><code>...
      public IQueryable&lt;Arc&gt; ByRun(Run run)
      {
          IQueryable&lt;Arc&gt; query = from o in AsQueryable()
                                       from r in o.Runs
                                       where r.Id == run.Id
                                       select o;
          return query;
      }
  ...
  </code></pre>
  
  <p>and I want to change my query method to return IEnumerable and to dispose quickly of the context, so want to use (something like) this:</p>
  
  <pre><code>...
      protected virtual IEnumerable&lt;T&gt; AsEnumerable()
      {
          using (IContextUnitOfWork unitOfWork = new EFUnitOfWork())
          {
              return unitOfWork.ObjectSet&lt;T&gt;().ToList();
          }
      }
  ...
  </code></pre>
  
  <p>The problem, of course, is that once the context is disposed, calling LINQ on the resulting IEnumerable set will fail. Thus, my thought is that I should bundle up the ByRun() method and pass it to AsEnumerable() to be used as a closure.</p>
  
  <p>While not my original language style, I learned closures in Ruby. There, what I'm trying to do would look something like this mixed up pseudo-code:</p>
  
  <pre><code>ByRun(Run run)
    AsEnumerable do |query|
      from o in query
             from r in o.Runs
             where r.Id == run.Id
             select o;
    end
  end
  </code></pre>
  
  <p>where the AsEnumerable method would open the context, perform the operation that was passed in, and return. I'm sure I can do this once I understand the syntax, so I'm looking for my desired AsEnumerable and ByRun methods implemented this way.</p>