nam nam - 1 year ago 55
C# Question

Error when using "Include" method on a LINQ Query

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; }

Answer Source

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.