【发布时间】: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