Skip to content

EF 10: Nullable complex property with PropertyValues.ToObject() creates instance instead of null #37249

@alienwareone

Description

@alienwareone

Bug description

When using a nullable complex type configured with ComplexProperty, calling OriginalValues.ToObject() when the original complex property value is null creates a complex type instance instead of returning null (same for CurrentValues.ToObject()).

Your code

#:package Npgsql.EntityFrameworkCore.PostgreSQL@10.0.0
#:property PublishAot=false

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

await using var context = new ProductContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Products.Add(new() { Name = "Product 1" });
await context.SaveChangesAsync();

context.ChangeTracker.Clear();
var product = await context.Products.FirstAsync();
var originalProduct = context.ChangeTracker.Entries().First().OriginalValues.ToObject();
;

public sealed class ProductContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql("Host=localhost;Username=postgres;Password=postgres;Database=Test")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.Entity<Product>().ComplexProperty(x => x.Price);
}

public sealed class Product
{
    public int Id { get; private set; }
    public required string Name { get; set; }
    public Price? Price { get; set; }
}

public sealed class Price
{
    public required decimal Amount { get; init; }
    public required int CurrencyId { get; init; }
}

Stack traces


Verbose output


EF Core version

10.0.0

Database provider

Npgsql.EntityFrameworkCore.PostgreSQL

Target framework

.NET 10.0

Operating system

Windows 11

IDE

VSCode

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions