首页 > 解决方案 > ef core include 总是创建左连接

问题描述

我想按导航属性过滤数据,所以我希望“包含”生成“内部联接”查询。正如其他问题的答案所说,我将属性设置为“必需”,但它不起作用。

    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:</p>

      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:</p>

      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]

版本:ef 核心 5.0

标签: c#.netentity-frameworkentity-framework-core

解决方案


推荐阅读