Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
    }
}
like image 952
nam Avatar asked Dec 06 '25 21:12

nam


1 Answers

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.

like image 149
Kirill Bestemyanov Avatar answered Dec 08 '25 11:12

Kirill Bestemyanov



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!