ef core 的 include 如何生成 inner join的语句

新手上路,请多包涵
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
        public int? Rating { get; set; }

        public List<Post> Posts { get; set; }
    }
    
    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int Rating { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>()
                .HasMany(b => b.Posts)
                .WithOne(p => p.Blog)
                .HasForeignKey(p => p.BlogId)
                .OnDelete(DeleteBehavior.NoAction).IsRequired();
}
using (var context = new BloggingContext())
{
        var blogs = context.Blogs
              .Include(blog => blog.Posts.Where(blog => blog.Content == "xxxx"))
              .ToList();
}

生成的SQL:

      SELECT [b].[BlogId], [b].[OwnerId], [b].[Rating], [b].[Url], [t].[PostId], [t].[AuthorId], [t].[BlogId], [t].[Content], [t].[Rating], [t].[Title]
      FROM [Blogs] AS [b]
      LEFT JOIN (
          SELECT [p].[PostId], [p].[AuthorId], [p].[BlogId], [p].[Content], [p].[Rating], [p].[Title]
          FROM [Posts] AS [p]
          WHERE [p].[Content] = N'xxxx'
      ) AS [t] ON [b].[BlogId] = [t].[BlogId]
      ORDER BY [b].[BlogId], [t].[PostId]

希望生成的SQL:

      SELECT [b].[BlogId], [b].[OwnerId], [b].[Rating], [b].[Url], [t].[PostId], [t].[AuthorId], [t].[BlogId], [t].[Content], [t].[Rating], [t].[Title]
      FROM [Blogs] AS [b]
      INNER JOIN (
          SELECT [p].[PostId], [p].[AuthorId], [p].[BlogId], [p].[Content], [p].[Rating], [p].[Title]
          FROM [Posts] AS [p]
          WHERE [p].[Content] = N'xxxx'
      ) AS [t] ON [b].[BlogId] = [t].[BlogId]
      ORDER BY [b].[BlogId], [t].[PostId]
阅读 2.3k
1 个回答
var blogs = context.Blogs.Where(blog => blog.Content == "xxxx");
    blogs.Include(p => p.Posts).SelectMany(d => d.Posts).Load();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进