无法使用FirstOrDefault()和condition编写包含查询 [英] Unable to write an Include query with FirstOrDefault() and condition

查看:105
本文介绍了无法使用FirstOrDefault()和condition编写包含查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

当执行对blogs1的查询时,我看到以下异常 blogs2查询按预期工作

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

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

推荐答案

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

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:

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

这篇关于无法使用FirstOrDefault()和condition编写包含查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆