【问题标题】:Unable to write an Include query with FirstOrDefault() and condition无法使用 FirstOrDefault() 和条件编写包含查询
【发布时间】:2019-10-11 19:36:11
【问题描述】:

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

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

我希望结果有第一个或默认博客以及作者“我”为该博客发布的第一个或默认帖子以及所有 cmets 的列表。

当查询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

【问题讨论】:

  • 您是否尝试过使用 Include(d=>d.Posts).Include(d=>Posts.Comments).ToList()?
  • 所以,帖子看起来像是博客对象上的导航属性,但我没有看到博客对象上的评论属性。我认为这是基于您提供的代码“.Include(x => x.Comment)”的违规行,因为我假设您的 Blog 对象没有名为“Comment”的导航属性
  • @MoeJallaq 我的要求是根据帖子过滤并首先执行或默认
  • @victor 更新问题,评论实际上是帖子上的导航属性
  • @Rufus L 这个问题不是重复的,我的要求是有条件地包含导航属性,即我想过滤 Blog , Posts 并且需要所有 cmets 用于第一个或默认帖子

标签: c# entity-framework-6


【解决方案1】:

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

【讨论】:

  • 感谢您的回复,我实际上在我的代码中使用了第二种方法。但实际上我想知道如何在不从数据库中获取所有与博客相关的帖子的情况下使用方法 1 来做同样的事情。
  • 根据我的要求,我使用了方法 2 和 FirstOrDefault 而不是 Where。
  • 使用方法一,不能只拉帖子。
  • 是的,山姆,我想通了。感谢您的回答。
猜你喜欢
  • 2021-09-25
  • 2011-01-23
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2014-03-29
  • 2021-05-22
  • 2010-11-11
  • 2023-03-11
相关资源
最近更新 更多