Left join via SelectMany + DefaultIfEmpty returns null outer entity instead of just null inner

オープン
#38,813 コメント 2 件 リアクション 0 件 担当者 1 名 GitHub で見る

メンテナーはふだん 2 日以内に返信

@AndriySvyryd がすでに取り組んでいます。

2026年8月19日 から。

評価

この issue はまだ評価されていません。

説明

area-query customer-reported
Bug description

Projecting an anonymous type that captures both the outer entity and the inner element inside SelectMany(s => s.Nav.Take(1).DefaultIfEmpty().Select(f => new { s, f })) returns rows in which the outer entity s is null, even though s comes from the outer table and its navigation is a required, non-nullable reference. The nulls occur on exactly the rows whose inner collection is empty, and the equivalent Select(s => new { s, s.Nav.Take(1).FirstOrDefault() }) query over the same data materializes all 40 outer entities correctly
("equivalent" in terms of results, not in terms of the same translated query)

This occurs in both EFC 10.0.11, and the EFC 11.0.0-preview.7.26381.103

Related to what was discussed in #30450

Your code

Full MRE:
https://github.com/AlmightyMRE/EFC_DefaultIfEmpty_Bug/blob/main/Program.cs

    var ids = await db.OCR.Where(x => x.Status == ProcessStatus.Pending).Select(x => x.Id).Take(40).ToListAsync();
    var query = db.OCR.Where(x => ids.Contains(x.Id));

    var broken = await query.SelectMany(s => s.FileData.UsedByFiles.Take(1).DefaultIfEmpty().Select(f => new { FileOcr = s, File = f })).ToListAsync();

    var control = await query.Select(s => new { FileOcr = s, File = s.FileData.UsedByFiles.Take(1).FirstOrDefault() }).ToListAsync();

    Console.WriteLine($"SelectMany+DefaultIfEmpty: rows {broken.Count}, {broken.Count(q => q.FileOcr is null)} FileOcr nulls, {broken.Count(q => q.File is null)} File nulls");
    Console.WriteLine($"Select+FirstOrDefault:     rows {control.Count}, {control.Count(q => q.FileOcr is null)} FileOcr nulls, {control.Count(q => q.File is null)} File nulls");

Output:

SelectMany+DefaultIfEmpty: rows 40, 14 FileOcr nulls, 14 File nulls
Select+FirstOrDefault:     rows 40, 0 FileOcr nulls, 14 File nulls
EF Core version

10.0.11

Database provider

Microsoft.EntityFrameworkCore.SqlServer

Target framework

.NET 10

Operating system

Windows 11

IDE

JetBrains Rider

主要言語
C#
スター
14.8k
フォーク
3.5k
平均マージ
3日 7時間
マージ済み PR(30日)
182

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

dotnet/efcore のほかの issue

dotnet/efcore の issue をすべて見る

似ている issue

C# の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。