Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this LINQ expression break my loop & conversion logic?
    text
    copied!<h3>Background</h3> <p><code>ArticleService</code> is a class that provides methods for front-end layers to facilitate business with the back-end.</p> <p>Two of its base responsibilities are to convert ViewModels (<code>ArticleViewModel</code>) to the appropriate Models (<code>Article</code>) when persisting data, and the reverse, convert Models to ViewModels when fetching data... so often that I created a private method building ViewModel objects:</p> <pre><code>private ArticleViewModel BuildViewModel(Article a) { return new ArticleViewModel { Title = a.Title /* all properties */ } } </code></pre> <p>Moving along, the <code>ArticleService</code> provides a method to fetch all articles from the data store, returning them as ViewModels: <code>public IEnumerable&lt;ArticleViewModel&gt; All()</code></p> <p>A calling class uses it like this: <code>var articleViewModels = _articleService.All();</code></p> <p>Simple, right?</p> <h3>Problem:</h3> <p>I originally wrote <code>All()</code> lazily with a classic <code>foreach</code> loop:</p> <pre><code>private IEnumerable&lt;ArticleViewModel&gt; All() { var viewModels = new List&lt;ArticleViewModel&gt;(); foreach (var article in _db.Articles) viewModels.Add(BuildViewModel(article)); return viewModels; } </code></pre> <p>It worked fine - <code>articleViewModels</code> was an instantiate list of all view models.</p> <p>Next, I used ReSharper to convert this loop to a LINQ statement for performance and prettiness, and then combined the assignment statement with the return statement. Result:</p> <pre><code>private IEnumerable&lt;ArticleViewModel&gt; All() { return _db.Articles.Select(article =&gt; BuildViewModel(article)).ToList(); } </code></pre> <p>I debugged the LINQ statement and the beast awakened: </p> <blockquote> <p>LINQ to Entities does not recognize the method 'ArticleViewModel BuildViewModel(Article)' and this method cannot be translated into a store expression. </p> </blockquote> <h3>Question - Why does this LINQ statement break my code?</h3> <p><em>Note: Stepping back to an explicit declaration, assignment, return worked with the LINQ statement, so I'm almost certain it's something to do with the lambda logic.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload