在我的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; }
}
}
答案 0 :(得分:1)
您不能在匿名类型的IQueryable
上使用Include。 Include是用于急切加载导航属性的方法。它只能在具有导航属性的IQueryable
实体上使用。
典型用法:
var qry = _context.Blogs.Include(p=>p.Posts).ToArray();
它返回每个帖子中加载了博客的Post数组。