【问题标题】:Error when using "Include" method on a LINQ Query在 LINQ 查询上使用“包含”方法时出错
【发布时间】:2017-01-18 19:21:21
【问题描述】:

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

【问题讨论】:

  • 我不完全确定您为什么认为这应该有效。您正在投影一个匿名类型,然后您仍然希望包含一个实体?导航属性在哪里?
  • 你可以为“博客”模型输入代码吗?
  • @Sampath 当然,它来自这个official ASP.NET tutorial。但作为参考,根据您的要求,我还将它包含在我帖子的 Model 部分中。
  • 我说得对,如果帖子存在,您想获取包含帖子的博客列表吗?
  • 您甚至不需要尝试包含您在选择新查询中指定的博客。

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


【解决方案1】:

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

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

它在每个帖子中返回带有加载博客的帖子数组。

【讨论】:

  • 我喜欢您提供的解决方案的简要说明,因为它帮助我理解了我的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2015-05-01
  • 2011-01-23
  • 1970-01-01
  • 2012-05-02
  • 2021-08-19
  • 2016-09-01
相关资源
最近更新 更多