Unable to write an Include query with FirstOrDefault() and condition

巧了我就是萌 提交于 2019-12-11 08:04:51

问题


I'm writing an entity framework query which needs Eager loading multiple levels based on condition.

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

I expect result to have first or default Blog and first or default Post for that blog by author "Me" and a list of all comments.

When query for blogs1is executed I see following exception blogs2 query works as expected

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:


FirstOrDefault executes the query and you can not use it inside Include as its purpose is to include navigational properties. You will need to modify the query to one of the below two ways:

Method 1: Its two two step process:

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

Method 2:

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


来源:https://stackoverflow.com/questions/58347487/unable-to-write-an-include-query-with-firstordefault-and-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!