[英]Unable to write an Include query with FirstOrDefault() and 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();
我希望结果有第一个或默认博客以及作者“我”为该博客发布的第一个或默认帖子以及所有评论的列表。
执行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 中使用它,因为它的目的是包含导航属性。 您需要将查询修改为以下两种方式之一:
方法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");
方法二:
var myPosts = context.Posts.Include(p => p.Blog).Include(p => p.Comments).Where(p => p.Author == "Me");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.