Skip to content

Required owned entity on a TPH derived type is materialized for an unrelated row #38659

Open

Description

@galaxy-atlas

Bug description

Using TPH, a derived type has a required OwnsOne navigation:

efcore-tph-required-owned-repro.zip

modelBuilder.Entity<CircleOverlay>(builder =>
{
    builder.OwnsOne(x => x.Shape);
    builder.Navigation(x => x.Shape).IsRequired();
});

The database contains only a LineOverlay and no CircleOverlay rows. However,
querying the base type still invokes the Circle constructor with null:

await db.Overlays.AsNoTracking().ToListAsync();
CircleOverlay rows in database: 0
Circle constructor called: point is null = True, radius = 0
System.ArgumentNullException: Value cannot be null. (Parameter 'point')

Expected

EF materializes the LineOverlay without invoking the Circle constructor,
because the row discriminator is LineOverlay.

Reproduction

Run the attached project:

dotnet run

Reproduced with:

  • EF Core / SQLite provider 10.0.10
  • .NET 10.0

This appears related to #31353, which was fixed in 8.0.3. Unlike that issue,
this owned navigation is explicitly configured as required. Making it optional
avoids the exception, but changes the model semantics: every CircleOverlay
must have a Circle.

Your code

A complete minimal runnable reproduction project is attached:

[EfCoreTphRequiredOwnedRepro.zip](replace-with-the-link-generated-by-GitHub)

Run it with:


dotnet run

Stack traces

Materializing the base TPH query...
Circle constructor called: point is null = True, radius = 0
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'point')
   at System.ArgumentNullException.Throw(String paramName)
   at System.ArgumentNullException.ThrowIfNull(Object argument, String paramName)
   at Circle..ctor(String point, Double radius) in C:\myfiles\mytemp\projects\efcore-tph-required-owned-repro\Program.cs:line 62
   at lambda_method84(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in C:\myfiles\mytemp\projects\efcore-tph-required-owned-repro\Program.cs:line 32

Verbose output


EF Core version

10.0.10

Database provider

Microsoft.EntityFrameworkCore.Sqlite

Target framework

.NET 10

Operating system

No response

IDE

No response

Activity

  1. AndriySvyryd commented on Jul 17, 2026

    @AndriySvyryd
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Summary

    This is a genuine bug. When a required owned entity (IsRequired()) is on a TPH-derived type, querying the base type throws an ArgumentNullException because EF attempts to materialize the owned entity for rows that belong to sibling discriminator types — rows where the owned entity's columns are NULL.

    Root Cause

    The fix for #31353 (shipped in EF 8.0.3) taught EF to generate a "null check" condition before materializing an owned entity when the entity is considered optional in the relational model. The optionality is computed in RelationalModel.PopulateOptionalTypes (src/EFCore.Relational/Metadata/Internal/RelationalModel.cs) by propagating the optional flag through FK chains:

    entityTypesToVisit.Enqueue(
        (referencingForeignKey.DeclaringEntityType, optional || !referencingForeignKey.IsRequiredDependent));

    For a required FK (IsRequiredDependent = true), !IsRequiredDependent = false, so the optional flag stays false. As a result table.IsOptional(Circle) returns false.

    In RelationalStructuralTypeShaperExpression.GenerateMaterializationCondition (src/EFCore.Relational/Query/RelationalStructuralTypeShaperExpression.cs), the null-check block is gated on:

    if (table.IsOptional(entityType))
    {
        // generates null-check guard for owned entity materialization
    }

    Because IsOptional is false for a required owned entity, no null-check is generated. When a LineOverlay row is read, EF still invokes the Circle constructor (with null column values) since it believes the owned entity can never be absent. The underlying issue is that even a required owned entity on a derived TPH type is effectively absent for rows of other discriminator types — the fix for #31353 addressed this for the optional case but not the required case.

    Reproduction Confirmed

    Reproduced on EF Core 10.0.10 (SQLite provider). Throws System.ArgumentNullException: Value cannot be null. (Parameter 'point') when querying context.Overlays.AsNoTracking().ToListAsync() on a DB that contains only LineOverlay rows.

    minimal repro
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    await using var context = new TestContext();
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();
    
    context.Overlays.Add(new LineOverlay { Start = "0,0", End = "1,1" });
    await context.SaveChangesAsync();
    
    Console.WriteLine($"CircleOverlay rows in database: {await context.Overlays.OfType<CircleOverlay>().CountAsync()}");
    
    // Throws ArgumentNullException — Circle constructor called with null values
    var overlays = await context.Overlays.AsNoTracking().ToListAsync();
    
    public class TestContext : DbContext
    {
        public DbSet<Overlay> Overlays { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlite("Data Source=repro.db")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Overlay>()
                .HasDiscriminator<string>("Discriminator")
                .HasValue<LineOverlay>("LineOverlay")
                .HasValue<CircleOverlay>("CircleOverlay");
            modelBuilder.Entity<CircleOverlay>(builder =>
            {
                builder.OwnsOne(x => x.Shape);
                builder.Navigation(x => x.Shape).IsRequired();
            });
        }
    }
    
    public abstract class Overlay { public int Id { get; set; } }
    public class LineOverlay : Overlay { public string? Start { get; set; } public string? End { get; set; } }
    public class CircleOverlay : Overlay { public Circle Shape { get; set; } = null!; }
    
    public class Circle
    {
        public Circle(string point, double radius) { ArgumentNullException.ThrowIfNull(point); Point = point; Radius = radius; }
        public string Point { get; set; } = null!;
        public double Radius { get; set; }
    }

    Regression Analysis

    Not a regression from 8.0.x. The fix for #31353 (8.0.3) only handled the optional owned-entity case. The required case has been broken since TPH + owned entity support was introduced. Removing .IsRequired() avoids the exception.

    Possible Fix Direction

    In RelationalModel.PopulateOptionalTypes, the entity should still be considered optional if its owner is a derived type in a TPH hierarchy:

    entityTypesToVisit.Enqueue(
        (referencingForeignKey.DeclaringEntityType,
         optional || !referencingForeignKey.IsRequiredDependent
                 || referencingForeignKey.DeclaringEntityType.BaseType != null));
  2. added this to the Backlog milestone on Jul 17, 2026
  3. self-assigned this
    on Jul 17, 2026
  4. added theissue type on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions