Skip to content

Unset properties on owned entities aren't sent to the database when saved #23824

@roji

Description

@roji

When saving, we send NULL for unset properties, but not when they're part of an owned entity (either required or optional).

Repro
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

ctx.Blogs.Add(new());
ctx.SaveChanges();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"...")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>(e =>
        {
            e.OwnsOne(b => b.OptionalOwnedThing);
            e.OwnsOne(b => b.RequiredOwnedThing);
            e.Navigation(b => b.RequiredOwnedThing).IsRequired(true);
            e.Navigation(b => b.OptionalOwnedThing).IsRequired(false);
        });
    }
}

public class Blog
{
    public int Id { get; set; }
    public string NonOwnedProperty { get; set; }
    public OptionalOwnedThing OptionalOwnedThing { get; set; }
    public RequiredOwnedThing RequiredOwnedThing { get; set; }
}

public class OptionalOwnedThing
{
    public string OptionalOwnedProperty { get; set; }
}

public class RequiredOwnedThing
{
    public string RequiredOwnedProperty { get; set; }
}

Logs:

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (24ms) [Parameters=[@p0=NULL (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      INSERT INTO [Blogs] ([NonOwnedProperty])
      VALUES (@p0);
      SELECT [Id]
      FROM [Blogs]
      WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();

/cc @AndriySvyryd

Metadata

Metadata

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions