Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF4 Include() with Projection

I am trying to do a simple query which involves both eager loading and projection and am having problems. I am using CodeFirst CTP5 but I beleive that this issue affects straight EF4 as well.

Here is my initial query:

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 results in the category property of article being null. If I take out the projection, it works just fine. After reading this, it seems to suggest that I need to do the include after the projection, so I changed the query 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.

"Unable to cast the type 'System.Linq.IQueryable1' to type 'System.Data.Objects.ObjectQuery1'. LINQ to Entities only supports casting Entity Data Model primitive types."

So, how do I do it?

like image 321
Paul Hiles Avatar asked Apr 10 '26 11:04

Paul Hiles


1 Answers

You could try:

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();
}
like image 57
LukLed Avatar answered Apr 17 '26 22:04

LukLed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!