EF4 Include () with projection

I am trying to make a simple request that includes impatient loading as well as projection, and I am having problems. I use CodeFirst CTP5, but I believe that this problem also affects direct EF4.

Here is my initial request:

public List<ArticleSummary> GetArticles()
    {
        var articlesQuery = _db.Articles.Include(article => article.Category).Select(article => new ArticleSummary
        {
            Article = article,
            CommentsCount = article.Comments.Count
        });

        return articlesQuery.ToList();
    }

This causes the category property to be null. If I pulled out a projection, it works fine. After reading this , it looks like I need to make an inclusion after projecting, so I changed the request to:

    public List<ArticleSummary> GetArticles()
    {
        var articlesQuery = _db.Articles.Select(article => new ArticleSummary
        {
            Article = article,
            CommentsCount = article.Comments.Count
        });

        articlesQuery = articlesQuery.Include(x => x.Article.Category);

        return articlesQuery.ToList();
    }

This results in an exception (see below), which is similar to this SO post .

"Cannot apply type 'System.Linq.IQueryable 1' to type 'System.Data.Objects.ObjectQuery1'. LINQ to Entities only supports casting Entity Data Model primitive types."

, ?

+3
1

:

public List<ArticleSummary> GetArticles()
{
    var articlesQuery = _db.Articles.Select(article => new
        {
            Article = article,
            Category = article.Category
            CommentsCount = article.Comments.Count
        }
    ).ToList().
    Select(
       x => new ArticleSummary() 
       {
            Article = x.Article,
            CommentsCount = x.CommentsCount
       }
    );

    return articlesQuery.ToList();
}
+4

Source: https://habr.com/ru/post/1783131/


All Articles