Skip to content

Comparison of nullable owned entity may return incorrect result (true when owned entity is not null) #31176

@OldrichDlouhy

Description

@OldrichDlouhy

Comparing nullable owned entity to null in Select methods returns incorrect result - the null comparison returns true even when the owned entity exists.

Steps to reproduce

Having model with Owner and Owned classes

/// <summary>
/// Owner
/// </summary>
public class Owner
{
    /// <summary>
    /// Id of the owner
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// Name
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Owned entity
    /// </summary>
    public Owned? Owned { get; set; }
}

public class Owned
{
    /// <summary>
    /// Property A
    /// </summary>
    public string? A { get; set; }

    /// <summary>
    /// Property B
    /// </summary>
    public string? B { get; set; }
}

Where Owner owns Owned

var ownerBuilder = modelBuilder.Entity<Owner>();

        ownerBuilder.HasKey(e => e.Id);
        ownerBuilder.Property(e => e.Id)
            .IsRequired()
            .ValueGeneratedOnAdd();

        ownerBuilder.Property(e => e.Name)
            .IsRequired()
            .HasMaxLength(64);

        ownerBuilder.OwnsOne(e => e.Owned, ownedBuilder =>
        {
            ownedBuilder.Property(o => o.A)
                .IsRequired(false)
                .HasMaxLength(64);

            ownedBuilder.Property(o => o.B)
                .IsRequired(false)
                .HasMaxLength(64);
        });

The query

var testOwner = new Owner
{
    Name = "test",
    Owned = new Owned
    {
        A = "AAA"
    }
};

dbContext.Add(testOwner);
dbContext.SaveChanges();

dbContext.Owners
    .AsNoTracking()
    .Select(e => new
    {
        e.Name,
        OwnedLoaded = e.Owned,
        OwnedIsNull = e.Owned == null
    })
    .SingleOrDefault()

Returns data (after serialization to JSON)

{"Name":"test","OwnedLoaded":{"A":"AAA","B":null},"OwnedIsNull":true}

Observe that the owned entity is returned, yet the OwnedIsNull is true.

This behavior is independent on database provider, tested with SQLite and MySQL providers.

See attached project for minimal reproduction

EFCoreBug.OwnedEntityNull.zip

Provider and version information

EF Core version: 7.0.8
Database provider: Microsoft.EntityFrameworkCore.Sqlite
Target framework: .NET 7.0
Operating system: Windows 10
IDE: Visual Studio 2022 17.6.4

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions