Should you initialize an owned entity navigation with = new() in EF Core?
Tested on EF Core 11.0.0: with nullable reference types, Address Address = new() makes an owned navigation required, which is fine. On an optional owned navigation the initializer silently loses edits. And = null! on a required owned type in its own table can end in 'The data is NULL at ordinal 1'.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
It depends on whether the owned value is required, and with nullable reference types enabled the declaration already decides that for you. On EF Core 11.0.0, public Address Address { get; set; } = new(); declares a non-nullable navigation, so EF configures the owned type as a required dependent. In that case = new() is safe and arguably better than = null!: EF always materializes an Address, edits are saved, and new owners always get their owned data written. The initializer is harmful on an optional owned navigation (Address? Address = new(), or any initializer with nullable reference types off): an owner with no stored address loads with a detached, untracked Address, and changes you make to it are silently dropped by SaveChanges.
Everything below was run against .NET 11.0.0 (SDK 11.0.100) with Microsoft.EntityFrameworkCore.Sqlite 11.0.0 and <Nullable>enable</Nullable>, on an in-memory SQLite database on macOS arm64. The behaviour lives in EF Core’s model building, change tracker and materializer, not in the SQLite provider, but the exact exception text quoted below is the one Microsoft.Data.Sqlite produces.
Why the question keeps coming up
Turn on nullable reference types and every non-nullable reference property without an initializer produces CS8618. Scalars get = "". Collection navigations get = [], and the EF docs say collection navigations “should always be non-nullable”. For reference navigations the nullable reference types page shows = null! instead, and there is history behind that: dotnet/efcore#18007, “Initializing reference navigation in constructor causes incorrect fixup”, showed EF Core 3.0 only fixing up the first Album.Artist when the constructor did Artist = new Artist(). It was fixed for EF Core 5.0, but “never initialize a reference navigation” stuck as a rule.
Owned types are where that rule feels wrong. An owned Address has no identity of its own, cannot be queried on its own, and is always loaded with its owner. Initializing it looks like initializing a value object. The Stack Overflow question that prompted this post asks exactly that, and the answers there disagree. So instead of arguing, here is what EF 11 does.
The declaration decides required vs optional
The model under test uses one owned type and several owners that differ only in how the navigation is declared:
// .NET 11.0.0, EF Core 11.0.0, C# 15, <Nullable>enable</Nullable>
public class Address
{
public static int Created;
public Address() => Created++;
public string? Street { get; set; }
public string? City { get; set; }
}
public class A { public int Id { get; set; } public Address? Address { get; set; } } // nullable, no initializer
public class B { public int Id { get; set; } public Address Address { get; set; } = new(); } // non-nullable, = new()
#nullable disable
public class B2 { public int Id { get; set; } public Address Address { get; set; } = new(); } // NRT off, = new()
#nullable enable
public class B3 { public int Id { get; set; } public Address? Address { get; set; } = new(); } // nullable, = new()
public class Ctx(DbContextOptions<Ctx> o) : DbContext(o)
{
public DbSet<A> A => Set<A>(); public DbSet<B> B => Set<B>();
public DbSet<B2> B2 => Set<B2>(); public DbSet<B3> B3 => Set<B3>();
protected override void OnModelCreating(ModelBuilder mb)
{
mb.Entity<A>().ToTable("A").OwnsOne(x => x.Address);
mb.Entity<B>().ToTable("B").OwnsOne(x => x.Address);
mb.Entity<B2>().ToTable("B2").OwnsOne(x => x.Address);
mb.Entity<B3>().ToTable("B3").OwnsOne(x => x.Address);
}
}
There is no IsRequired() call anywhere, yet asking the model gives:
db.Model.FindEntityType(typeof(B))!.FindNavigation("Address")!.ForeignKey.IsRequiredDependent
A: IsRequiredDependent=False
B: IsRequiredDependent=True
B2: IsRequiredDependent=False
B3: IsRequiredDependent=False
EF reads the nullable annotation on the navigation. A non-nullable Address Address in a nullable-enabled file is a required owned navigation by convention, exactly as if you had written mb.Entity<B>().Navigation(x => x.Address).IsRequired(). The initializer plays no part in that decision. So the real question splits in two: is = new() fine on a required owned navigation, and is it fine on an optional one?
With table splitting (the default), the owned columns live in the owner’s table and are always nullable, whatever the requiredness:
CREATE TABLE "B" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_B" PRIMARY KEY AUTOINCREMENT,
"Address_Street" TEXT NULL,
"Address_City" TEXT NULL
)
For the optional A, EF 11 also logs a warning when the model is built, because Address has only nullable properties:
The entity type 'A.Address#Address (Address)' is an optional dependent using table sharing
without any required non shared column that could be used to identify whether the entity exists.
If all nullable properties contain a 'null' value in database then an object instance won't be
created in the query.
Required owned navigation with = new(): fine
Insert a row with raw SQL so its address columns are all NULL (a legacy row, or a column added later), then load it as B:
b.Addressis non-null withStreet == null, and the change tracker showsAddress {BId: 1} Unchangednext to the owner. A required dependent is always materialized.- Editing
b.Address.Street = "Edited"and callingSaveChangespersists it; reloading returns'Edited'. - Changing only an owner property issues
UPDATE ... SET "Name" = @p0and nothing else. No spurious writes. db.B.AsNoTracking().Select(x => x.Address).Single()returns a non-nullAddresstoo, so entity queries and projections agree.- A new
Bsaved without touching the address writes the owned columns explicitly:INSERT INTO "B" ("Id", "Address_City", "Address_Street").
The one cost: a static counter in the Address constructor shows that materializing one B row whose address has data constructs two Address objects. The initializer runs in the constructor, then EF assigns the materialized instance over it. One wasted allocation per owned navigation per entity, which only matters for queries that return very large numbers of rows.
If the owned type is mapped to its own table (OwnsOne(x => x.Address, o => o.ToTable("B_Address"))), the initializer means every new owner also gets a dependent row, even if every column in it is NULL. For a required value that is the correct outcome.
Required owned navigation with = null!: the trap
The advice you will usually see for a required owned type is: declare it non-nullable and write = null!. The model is identical to B. What changes is what happens when some code path forgets to set the value, because EF 11 does not check on save that a required owned dependent exists:
// .NET 11.0.0, EF Core 11.0.0
public class E { public int Id { get; set; } public Address Address { get; set; } = null!; } // own table
public class F { public int Id { get; set; } public Address Address { get; set; } = null!; } // table splitting
mb.Entity<E>().ToTable("E").OwnsOne(x => x.Address, o => o.ToTable("E_Address"));
mb.Entity<E>().Navigation(x => x.Address).IsRequired();
mb.Entity<F>().ToTable("F").OwnsOne(x => x.Address);
mb.Entity<F>().Navigation(x => x.Address).IsRequired();
db.E.Add(new E { Id = 1 }); // forgot Address
db.F.Add(new F { Id = 1 }); // forgot Address
db.SaveChanges(); // succeeds: INSERT INTO "E" ("Id") ...; INSERT INTO "F" ("Id") ...
No exception, no warning. The table-splitting variant F gets away with it: reading it back materializes an Address with null properties. The separate-table variant E does not:
db.E.Count(); // 1
db.E.ToList(); // throws
SELECT "e"."Id", "e0"."EId", "e0"."City", "e0"."Street"
FROM "E" AS "e"
LEFT JOIN "E_Address" AS "e0" ON "e"."Id" = "e0"."EId"
System.InvalidOperationException: The data is NULL at ordinal 1. This method can't be called on NULL values. Check using IsDBNull before calling.
at Microsoft.Data.Sqlite.SqliteValueReader.GetInt64(Int32 ordinal)
at Microsoft.Data.Sqlite.SqliteDataReader.GetInt32(Int32 ordinal)
at lambda_method261(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
The materializer trusts the required configuration and reads the dependent’s key column without a null check. One bad row breaks every query that returns it, far away from the code that forgot to assign the address. The same model with = new() instead of = null! inserted an E_Address row and read back without error.
If an empty Address is not a valid domain value either, the better fix is to make the value impossible to forget:
// .NET 11.0.0, EF Core 11.0.0, C# 15
public class Customer
{
private Customer() { } // used by EF; Address is assigned during materialization
public Customer(string name, Address address) { Name = name; Address = address; }
public int Id { get; private set; }
public string Name { get; private set; } = "";
public Address Address { get; private set; } = null!;
}
Here = null! is honest, because the only public way to create a Customer passes an Address.
Optional owned navigation with = new(): silent data loss
Now the case the original question was worried about. B3 declares Address? Address { get; set; } = new();, so the navigation is optional, and the initializer still runs. Load a B3 row whose address columns are all NULL:
// .NET 11.0.0, EF Core 11.0.0
var b3 = db.B3.Single();
Console.WriteLine(b3.Address is null); // False
Console.WriteLine(db.Entry(b3).Reference(x => x.Address).TargetEntry!.State); // Detached
b3.Address!.Street = "Edited";
db.ChangeTracker.DetectChanges();
// ChangeTracker: B3 {Id: 1} Unchanged <- no Address entry at all
db.SaveChanges(); // no exception, no SQL
// in a new context
db.B3.Single().Address?.Street; // null
EF found no dependent in the row, so it never assigned the navigation and never tracked anything for it. The object sitting in b3.Address is the one the initializer created, and EF does not know it exists: DetectChanges does not pick it up as a new owned entity, SaveChanges writes nothing, and the edit is gone. The same happens when the owned type has its own table and the owner has no dependent row: the Address is Detached and the edit is lost.
There are two more inconsistencies in that configuration:
db.B3.AsNoTracking().Select(x => x.Address).Single()returnsnullfor the same row, because noB3is constructed and the initializer never runs. Code that handles both entities and projections gets two different answers.- With nullable reference types off (
B2), the navigation is optional and behaves exactly likeB3. Projects that never enabled NRT and added= new()to dodge null checks are the most likely to hit this.
So on an optional owned navigation the initializer is not a harmless convenience. It hides the “no address” state behind an object that looks real and is not tracked.
How to model an optional owned value
If “no address” is a legitimate state, keep it representable.
Nullable navigation, no initializer
public Address? Address { get; set; } with plain OwnsOne, like A above. Clearing it (a.Address = null) issues UPDATE ... SET "Address_City" = NULL, "Address_Street" = NULL and reloads as null. The caveat is the one the warning names: an address whose properties are all null is indistinguishable from no address. Usually that is fine, since an address with no street and no city is not an address.
Add a required marker property
If an all-null value must survive the round trip, give the owned type one required column:
// .NET 11.0.0, EF Core 11.0.0
public class AddressWithMarker
{
public string? Street { get; set; }
public string? City { get; set; }
public bool Exists { get; set; } = true;
}
mb.Entity<I>().OwnsOne(x => x.Address, o => o.Property(a => a.Exists).IsRequired());
The column is still "Address_Exists" INTEGER NULL in the table, because owned columns under table splitting are always nullable, but EF uses its value to decide whether the dependent exists. In the test, new I { Id = 1 } reloaded with Address == null and new I { Id = 2, Address = new AddressWithMarker() } reloaded as a non-null, otherwise empty address.
Switch to an optional complex type
Since EF Core 10, a complex property can be optional by declaring it nullable. Complex types fit value objects better than owned types: no hidden key, no identity, no tracking-by-reference surprises like the detached Address above. They have the same all-null ambiguity, but EF enforces it at model validation instead of logging a warning:
System.InvalidOperationException: The optional complex property 'H.Address#Address (Address).Address'
is mapped to columns by flattening the contained properties into its container's table; this mapping
requires at least one required property - to allow distinguishing between 'null' and empty values -
but the complex type contains only optional properties. Configure the property with a shadow
discriminator by adding a call to 'HasDiscriminator()' on the complex property configuration.
Following the message:
// .NET 11.0.0, EF Core 11.0.0
public class H { public int Id { get; set; } public Address? Address { get; set; } }
mb.Entity<H>().ComplexProperty(x => x.Address, c => c.HasDiscriminator());
EF adds an "Address_Discriminator" TEXT NULL column, and all three states round-trip:
H1: Address null? True, Street='' // never set
H2: Address null? False, Street='Main St'
H3: Address null? False, Street='' // new Address() with all-null fields
For a new model on EF Core 10 or 11 this is the cleanest option. The broader trade-offs are covered in complex types vs owned entities in EF Core 11, and moving an existing mapping across is walked through in how to map a complex type instead of an owned entity.
Gotchas worth knowing
- Do not carry this over to regular entity navigations.
public Category Category { get; set; } = new();on a normal relationship creates a brand-newCategoryentity that EF will try to insert, or that fixup replaces. The docs’ reluctance to initialize reference navigations is about that case, and it still applies. - Collections are the opposite.
public List<Address> Addresses { get; set; } = [];forOwnsManyis correct. An empty collection is not ambiguous. - A tracking projection of an owned type throws.
db.B.Select(x => x.Address).Single()withoutAsNoTracking()fails with “A tracking query is attempting to project an owned entity without a corresponding owner in its result”. That is unrelated to the initializer, but you will hit it the moment you try to inspect the projection behaviour described above. - Check the tracker when in doubt. If an edit “does not save”, checking whether the instance is tracked immediately shows the
Detachedowned entry, which is the signature of the optional-plus-initializer case. - The instance you hold after
SaveChangesis not refreshed by the initializer. Setting an optional navigation tonulland saving leaves itnullin memory; only the next query constructs a new owner. The post on what EF Core writes back into an entity after SaveChangesAsync covers what does change in place.
The decision in three lines
- Required owned value (non-nullable navigation under NRT):
= new()is safe, and safer than= null!when the owned type has its own table. A constructor that takes the value is better still. - Optional owned value:
Address?with no initializer. Add a required marker property if an all-null value must be kept, or use an optional complex type withHasDiscriminator()on EF Core 10+. - Never pair
= new()with an optional owned navigation: edits to the placeholder instance are silently discarded.
Sources
- Working with nullable reference types, EF Core docs
- Owned entity types: mapping owned types with table splitting, EF Core docs
- Complex types: optional complex types, EF Core docs
- What’s new in EF Core 10: complex types
- dotnet/efcore#18007, “Initializing reference navigation in constructor causes incorrect fixup”
- Default value for a navigation to an owned entity, Stack Overflow
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.