无法使用 FirstOrDefault() 和条件编写包含查询
Unable to write an Include query with FirstOrDefault() and condition
我正在编写一个 entity framework 查询,它需要根据条件预先加载多个级别。
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();
我希望结果包含作者 "Me" 的第一个或默认博客和第一个或默认 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
FirstOrDefault 执行查询,您不能在 Include 中使用它,因为它的目的是包含导航属性。您需要将查询修改为以下两种方式之一:
方法一:其二两步过程:
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");
方法二:
var myPosts = context.Posts.Include(p => p.Blog).Include(p => p.Comments).Where(p => p.Author == "Me");
我正在编写一个 entity framework 查询,它需要根据条件预先加载多个级别。
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();
我希望结果包含作者 "Me" 的第一个或默认博客和第一个或默认 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
FirstOrDefault 执行查询,您不能在 Include 中使用它,因为它的目的是包含导航属性。您需要将查询修改为以下两种方式之一:
方法一:其二两步过程:
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");
方法二:
var myPosts = context.Posts.Include(p => p.Blog).Include(p => p.Comments).Where(p => p.Author == "Me");