在LINQ查询上使用“包含”方法时出错

时间:2016-09-11 01:03:54

标签: c# entity-framework linq asp.net-core entity-framework-core

在我的ASP.NET MVC Core项目中的以下LINQ查询中,我收到以下错误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());
}

模型:来自此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; }
    }
}

1 个答案:

答案 0 :(得分:1)

您不能在匿名类型的IQueryable上使用Include。 Include是用于急切加载导航属性的方法。它只能在具有导航属性的IQueryable实体上使用。 典型用法:

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

它返回每个帖子中加载了博客的Post数组。