title: Implement IQueryable wrapper to translate result objects
body: <p><strong>Update 2013-08-22:</strong></p>
  
  <p>After having a look at the 'Building an IQueryable provider series' (thanks for the link!) I got a bit further. I updated the code accordingly. It is still not fully working though. If I understand the tutorial correctly, the <code>GetEnumerator</code> is invoked in case multiple elements are requested (e.g. by a <code>ToList()</code> call on the queryable, or any aggregation function). So all the <code>GetEnumerator</code> implementation of the wrapper has to do is call an <code>Execute</code> on the provider and pass the queryable's expression. In the other case, if only a single element is requested, <code>Execute</code> is called directly. The queryable's expression also reflects whether it is for a single or multiple elements. Is this correct?  </p>
  
  <p>Unfortunately now I get an InvalidOperationException saying <em>'Sequence contains more than one element'</em> when calling <code>Execute</code> on the source query provider. What does this mean? I just pass the expression without any translation since the same types are involved as mentioned above. The translatation bit with <code>IEnumerable</code> in the code is probably incomplete, but for now I don't even get to that point.</p>
  
  <hr>
  
  <p>I'm trying to implement a simple IQueryable wrapper using a single underlying IQueryable as the data source which calls a translation function for each result object.</p>
  
  <p>I thought this would be relatively trivial since the only thing the wrapper has to do is translating. However I couldn't get my implementation to work.</p>
  
  <p>See below for what I got so far. For some queries it is working but I receive a <strike>StackOverflowException</strike> InvalidOperationException at some point. <strike>I guess this happens due to the cyclic association between my queryable and my query provider. But I do not understand how to implement this correctly.</strike></p>
  
  <p><strong>Here my questions and thoughts on it:</strong></p>
  
  <p><strike>1. Why does the IQueryable have a Provider which in turn returns an IQueryable again? Doesn't this call for endless recursion?</strike></p>
  
  <p><strike>2. Why is it not enough to implement IEnumerator? Why does FirstOrDefault for instance not use the enumerator to get the element? When I debugged the application GetEnumerator() was not called by FirstOrDefault() on my queryable.</strike></p>
  
  <p><strike>3. Since the enumerator is not used in every case, where is the correct point to call the translation function? The Execute-methods of the QueryProvider seemed to be the right place. But do I still need the translation call in the Enumerator for some cases?</strike> <em>Update:</em> I know realized that I need to provide my own <code>IEnumerable</code> implementation providing the <code>TranslatingEnumerator</code> and return this enumerable from my <code>Execute</code> method. In order to get the enumerator <code>GetEnumerator</code> calls <code>Execute</code> (see below). The LINQ code requesting the enumerator seems to make sure that the expression actually returns an <code>IEnumerable</code>.</p>
  
  <p><strong>Some side notes on the code:</strong></p>
  
  <ul>
  <li><p>The translation source type is named <em>TDatabaseEntity</em>, the translation target type is named <em>TBusinessEntity</em>.</p></li>
  <li><p>I'm essentially providing an IQueryable which takes the result objects retrieved from an underlying IQueryable and translates them to the TBusinessEntity <strike>type</strike> <em>objects</em>.</p></li>
  <li><p>I'm aware that the Expression also needs to be translated. However I set this aside since in my actual application I'm using the same types for TBusinessEntity and TDatabaseEntity, so the Expression can be passed straight through.</p></li>
  <li><p>The result objects still need to be translated to other instances though, despite being of the same type. <em>Update:</em> My translation layer is working already within my application and also takes care of related entities. It's just the 'implementing an IQueryable wrapper' thing I'm stuck with.</p></li>
  <li><p><strike>I'm afraid the whole implementation is incorrect</strike> -- the TODOs in the code are just my own notes.</p></li>
  </ul>
  
  <p><strong>Background:</strong> I'm kind of implementing my own detaching of entities received from DbContext within my data access layer to prevent my business layer from getting in touch with the actual entities -- due to some bugs with EF and other requirements I can't directly use EF detached entities.</p>
  
  <p><em>Thanks for your help!</em></p>
  
  <h2>IQueryable implementation</h2>
  
  <pre><code>internal class TranslatingQueryable&lt;TDatabaseEntity, TBusinessEntity&gt; : IQueryable&lt;TBusinessEntity&gt;
  {
      private readonly IQueryProvider _provider;
      private readonly IQueryable&lt;TDatabaseEntity&gt; _source;
  
      internal TranslatingQueryable(TranslatingQueryProvider provider, IQueryable&lt;TDatabaseEntity&gt; source)
      {
          Guard.ThrowIfArgumentNull(provider, "provider");
          Guard.ThrowIfArgumentNull(source, "source");
  
          _provider = provider;
          _source = source;
      }
  
      internal TranslatingQueryable(Func&lt;object, object&gt; translateFunc, IQueryable&lt;TDatabaseEntity&gt; databaseQueryable)
          : this(new TranslatingQueryProvider(translateFunc, databaseQueryable.Provider), databaseQueryable)
      {
      }
  
      public IEnumerator&lt;TBusinessEntity&gt; GetEnumerator()
      {
          return ((IEnumerable&lt;TBusinessEntity&gt;)Provider.Execute(Expression)).GetEnumerator();
      }
  
      IEnumerator IEnumerable.GetEnumerator()
      {
          return ((IEnumerable)Provider.Execute(Expression)).GetEnumerator();
      }
  
      public Expression Expression
      {
          get
          {
              return _source.Expression;
          }
      }
  
      public Type ElementType
      {
          get
          {
              return typeof(TBusinessEntity);
          }
      }
  
      public IQueryProvider Provider
      {
          get
          {
              return _provider;
          }
      }
  }
  </code></pre>
  
  <h2>IQueryProvider implementation</h2>
  
  <pre><code>public class TranslatingQueryProvider : IQueryProvider
  {
      private readonly Func&lt;object, object&gt; _translateFunc;
      private readonly IQueryProvider _databaseQueryProvider;
  
      public TranslatingQueryProvider(Func&lt;object, object&gt; translateFunc, IQueryProvider databaseQueryProvider)
      {
          _translateFunc = translateFunc;
          _databaseQueryProvider = databaseQueryProvider;
      }
  
      public IQueryable CreateQuery(Expression expression)
      {
          var databaseQueryable = _databaseQueryProvider.CreateQuery&lt;object&gt;(expression);
  
          return new TranslatingQueryable&lt;object, object&gt;(this, databaseQueryable);
      }
  
      public IQueryable&lt;TElement&gt; CreateQuery&lt;TElement&gt;(Expression expression)
      {
          var databaseQueryable = _databaseQueryProvider.CreateQuery&lt;object&gt;(expression);
  
          return new TranslatingQueryable&lt;object, TElement&gt;(this, databaseQueryable);
      }
  
      public object Execute(Expression expression)
      {
          return Execute&lt;object&gt;(expression);
      }
  
      public TResult Execute&lt;TResult&gt;(Expression expression)
      {
          // TODO This call throws an InvalidOperationException if an enumeration is requested
          var databaseResult = _databaseQueryProvider.Execute&lt;TResult&gt;(expression);
  
          var databaseEnumerable = databaseResult as IEnumerable;
          if (databaseEnumerable != null)
          {
              if (typeof(TResult).IsAssignableFrom(typeof(IEnumerable)))
              {
                  throw new InvalidOperationException();
              }
  
              return (TResult)(object)new TranslatingEnumerable(databaseEnumerable, _translateFunc);
          }
          else
          {
              return (TResult)_translateFunc(databaseResult);
          }
      }
  
      private class TranslatingEnumerable : IEnumerable
      {
          private readonly TranslatingEnumerator _enumerator;
  
          public TranslatingEnumerable(IEnumerable databaseEnumerable, Func&lt;object, object&gt; translateFunc)
          {
              _enumerator = new TranslatingEnumerator(translateFunc, databaseEnumerable.GetEnumerator());
          }
  
          public IEnumerator GetEnumerator()
          {
              return _enumerator;
          }
      }
  }
  </code></pre>
  
  <h2>IEnumerator implementation</h2>
  
  <pre><code>internal class TranslatingEnumerator : IEnumerator
  {
      private readonly Func&lt;object, object&gt; _translateFunc;
      private readonly IEnumerator _databaseEnumerator;
  
      internal TranslatingEnumerator(Func&lt;object, object&gt; translateFunc, IEnumerator databaseEnumerator)
      {
          _translateFunc = translateFunc;
          _databaseEnumerator = databaseEnumerator;
      }
  
      public bool MoveNext()
      {
          return _databaseEnumerator.MoveNext();
      }
  
      public void Reset()
      {
          _databaseEnumerator.Reset();
      }
  
      public object Current
      {
          get
          {
              return _translateFunc(_databaseEnumerator.Current);
          }
      }
  
      object IEnumerator.Current
      {
          get
          {
              return Current;
          }
      }
  }
  </code></pre>