First I will explain what I am trying to do.
I am trying to grab a list of news articles from my entity framework and convert them to another object. However I get this exception:
System.NotSupportedException: LINQ to Entities does not recognize the method 'Database.Entity.DataTransferObjects.NewsObject FromNews(Database.Entity.News)' method, and this method cannot be translated into a store expression.
This is my code:
IEnumerable<NewsObject> news_articles = context.GetLatestNews(0);
public IEnumerable<NewsObject> GetLatestNews(int start)
{
IQueryable<NewsObject> latest_news = context.News.Where(news => news.Published).Select(articles => NewsObject.FromNews(articles));
IEnumerable<NewsObject> latest_news_ordered = latest_news.OrderByDescending(news => news.PublishedDate).Skip(start).Take(5);
return latest_news_ordered;
}
This is my FromNews part:
public static NewsObject FromNews(News news)
{
return new NewsObject
{
Id = news.Id,
Permalink = news.Permalink,
Subject = news.Subject,
Summary = news.Summary,
Content = news.Content,
Thumbnail = news.Thumbnail,
Published = news.Published,
PublishedDate = news.PublishedDate,
PublishedBy = news.PublishedBy,
CategoryId = news.CategoryId,
Publisher = MemberObject.FromMember(news.Publisher),
Category = CategoryObject.FromCategory(news.Category)
};
}
I read it’s a problem with the way LINQ is built/used but none of them provided a work around for what I am doing. I am trying to make code tiday :)!
It should work if you do it this way:
By invoking ToList() on your query, EF hits the db and no longer builds expression trees into your iqueryable. After the query is executed, it will pass to your FromNews method.
Update
To address the Skip and Take excerpts from comments, something like this could be done:
Reply to comments
Sorry I didn’t realize you were converting from
IQueryabletoIEnumerable. You can do this by calling the.AsEnumerable()method on theIQueryableinstance. I have updated the code posted.I have also updated the code to invoke
.Skipand.Takebefore.OrderByDescending. This makes sense because if you skip and take before ordering, your results will only be ordered within the 5 records you take. You need to order, then skip and take.Also see Daniel Hilgarth’s answer regarding deferred execution on the
.Selectmethod.