无法使用FirstOrDefault()和条件

时间:2019-10-11 19:36:11

标签: c# entity-framework-6

我正在编写一个实体框架查询,该查询需要Eager根据条件加载多个级别。

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(); 

我希望结果具有作者“我”的第一个或默认Blog和该博客的第一个或默认Post,以及所有评论的列表。

执行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

1 个答案:

答案 0 :(得分:1)

FirstOrDefault执行查询,您不能在Include中使用它,因为它的目的是包括导航属性。您将需要将查询修改为以下两种方式之一:

方法1:它的两个两步过程:

var blogs1 = context.Blogs
    .Include(x => x.Posts.Select(p => p.Comments))
**//     .Include(x => x.Comment) // This include is incorrect.**
    .FirstOrDefault(x => x.Posts.Any(h => h.Author == "Me"));

var myPosts = blogs1?.Posts.Where(p => p.Author == "Me");

方法2:

var myPosts = context.Posts.Include(p => p.Blog).Include(p => p.Comments).Where(p => p.Author == "Me");