【发布时间】:2019-10-11 19:36:11
【问题描述】:
我正在编写一个实体框架查询,它需要根据条件加载多个级别。
var blogs1 = context.Blogs
.Include(x => x.Posts.FirstOrDefault(h => h.Author == "Me"))
.Include(x => x.Comment)
.FirstOrDefault();
public class Blog
{
public int BlogId { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Author { get; set; }
public int BlogId { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int PostId
public int CommentId { get; set; }
public string CommentValue { get; set;}
}
var blogs2 = context.Blogs
.Include("Posts.Comments")
.ToList();
我希望结果有第一个或默认博客以及作者“我”为该博客发布的第一个或默认帖子以及所有 cmets 的列表。
当查询blogs1被执行时,我看到以下异常
blogs2 查询按预期工作
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path
【问题讨论】:
-
您是否尝试过使用 Include(d=>d.Posts).Include(d=>Posts.Comments).ToList()?
-
所以,帖子看起来像是博客对象上的导航属性,但我没有看到博客对象上的评论属性。我认为这是基于您提供的代码“.Include(x => x.Comment)”的违规行,因为我假设您的 Blog 对象没有名为“Comment”的导航属性
-
@MoeJallaq 我的要求是根据帖子过滤并首先执行或默认
-
@victor 更新问题,评论实际上是帖子上的导航属性
-
@Rufus L 这个问题不是重复的,我的要求是有条件地包含导航属性,即我想过滤 Blog , Posts 并且需要所有 cmets 用于第一个或默认帖子
标签: c# entity-framework-6