3

In my following LINQ Query in an ASP.NET MVC Core project, I'm getting the following error Unable to cast object of type 'System.Linq.Expressions.NewExpression' to type 'System.Linq.Expressions.MemberExpression'. The error occurs on the last line of the code below:

public async Task<IActionResult> Index()
{
    var qry = from b in _context.Blogs
                join p in _context.Posts on b.BlogId equals p.BlogId into bp
                from c in bp.DefaultIfEmpty()
                select new { b.BlogId, b.Url, c.Title, c.Content, c.Blog };
    var bloggingContext = qry.Include(p => p.Blog);
    return View(await bloggingContext.ToListAsync());
}

Model: From this official ASP.NET tutorial.

namespace ASP_Core_Blogs.Models
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }

        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}
8
  • 6
    I'm not entirely sure why you think this should work. You are projecting an anonymous type and then you still expecting to include an entity? Where would the navigation properties be? Commented Sep 11, 2016 at 1:20
  • can you put a code for 'Blog' model ? Commented Sep 11, 2016 at 3:28
  • @Sampath Sure, its from this official ASP.NET tutorial. But for reference, and per you request, I've also included it in Model section of my post. Commented Sep 11, 2016 at 3:35
  • Am I right then you want to get list of blogs with posts if posts exists? Commented Sep 11, 2016 at 5:55
  • 1
    You shouldn't even need to try to include blog as you've specified it in the select new query. Commented Sep 11, 2016 at 13:28

1 Answer 1

2

You cannot use Include on IQueryable of anonymous type. Include is method for eager loading of navigation properties. It can be used only on IQueryable of Entity with navigation properties. Typical usage:

var qry = _context.Blogs.Include(p=>p.Posts).ToArray();

it returns array of Post with loaded Blog in each post.

Sign up to request clarification or add additional context in comments.

1 Comment

I like a brief explanation you provided of your solution as it helped me understand my mistakes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.