在 LINQ 查询上使用"Include"方法时出错



在我的以下LINQ查询在一个ASP。. NET MVC核心项目,我得到以下错误Unable to cast object of type 'System.Linq.Expressions.NewExpression' to type 'System.Linq.Expressions.MemberExpression'。错误发生在下面代码的最后一行:

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:从这个官方ASP。网络教程。

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

不能在匿名类型的IQueryable上使用Include。包括用于即时加载导航属性的方法。只能在具有导航属性的实体的IQueryable上使用。典型用途:

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

返回每篇文章中加载博客的文章数组。

最新更新