dotnet/efcore · error · InvalidOperationException
The property '{1_entityType}.{0_property}' contains null, bu
Error message
The property '{1_entityType}.{0_property}' contains null, but the property is marked as required. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values. What it means
Thrown at serialization time (CosmosStructuralTypeSerializer.InstanceSerializationContext.ValidateNull for IProperty) when EF Core is writing an entity to Cosmos and a non-nullable property's CLR value is null. The Cosmos provider serializes the whole entity graph to JSON via CosmosStructuralTypeSerializer, so a null on a required scalar property violates the model contract and is rejected before the document is saved. The message is CoreStrings.PropertyConceptualNull and suggests EnableSensitiveDataLogging to reveal the entity key in the message.
Source
Thrown at src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs:428
{
if (!discriminatorProperty.IsShadowProperty())
{
return discriminatorProperty.GetGetter().GetClrValue(instance!);
}
var instanceType = instance!.GetType();
return structuralType.GetDerivedTypesInclusive().First(t => t.ClrType == instanceType).GetDiscriminatorValue();
}
public void SetOrdinal(IProperty ordinalKeyProperty, int? ordinal)
{
}
public void ValidateNull(IProperty property, ITypeBase structuralType)
{
if (!property.IsNullable)
{
throw new InvalidOperationException(CoreStrings.PropertyConceptualNull(property.Name, structuralType.DisplayName()));
}
}
public void ValidateNull(IComplexProperty complexProperty, ITypeBase structuralType)
{
if (!complexProperty.IsNullable)
{
throw new InvalidOperationException(CoreStrings.PropertyConceptualNull(complexProperty.Name, structuralType.DisplayName()));
}
}
public void ValidateNull(INavigation navigation, ITypeBase structuralType)
{
if (navigation.ForeignKey.IsRequired)
{
throw new InvalidOperationException(CoreStrings.PropertyConceptualNull(navigation.Name, structuralType.DisplayName()));
}
}View on GitHub (pinned to dbf9771522)
Solutions
- Set the property to a non-null value before SaveChanges, or initialize it in the entity constructor / property default.
- Make the property nullable in the model (CLR nullable type, or .IsRequired(false)) if null is a valid domain value for Cosmos documents.
- Run with EnableSensitiveDataLogging() once to capture the offending entity key, then locate the specific entity in tracking code.
- Audit change-tracking code paths (Add/Update) to ensure required scalars are populated for every entity type listed in the error.
Example fix
// before
var order = new Order { Id = 42 }; // RequiredProp never set
ctx.Add(order);
await ctx.SaveChangesAsync(); // throws PropertyConceptualNull on Order.RequiredProp
// after
var order = new Order { Id = 42, RequiredProp = "default" };
// or in OnModelCreating: modelBuilder.Entity<Order>().Property(o => o.RequiredProp).IsRequired(false); Defensive patterns
Strategy: validation
Validate before calling
// Validate required scalar properties before SaveChanges
var required = db.Model.FindEntityType(typeof(Order))!
.GetProperties()
.Where(p => !p.IsNullable)
.ToList();
foreach (var entry in db.ChangeTracker.Entries<Order>())
{
foreach (var p in required)
{
if (p.GetGetter().GetClrValue(entry.Entity) is null)
throw new InvalidOperationException($"{entry.Entity.GetType().Name}.{p.Name} is required but null.");
}
} Type guard
static bool HasAllRequiredScalars<TEntity>(TEntity entity, IModel model)
{
var et = model.FindEntityType(typeof(TEntity));
if (et is null) return true;
foreach (var p in et.GetProperties().Where(p => !p.IsNullable))
{
if (p.GetGetter().GetClrValue(entity!) is null) return false;
}
return true;
} Try / catch
try
{
await db.SaveChangesAsync(ct);
}
catch (InvalidOperationException ex) when (ex.Message.Contains("contains null, but the property is marked as required"))
{
// log, enable EnableSensitiveDataLogging to get the key, then surface a domain error
throw new DomainValidationException("A required property was null at save time.", ex);
} Prevention
- Use non-nullable C# reference types and required() in the model so the compiler flags null assignments.
- Initialize required properties in the entity constructor or via property defaults.
- Validate entities in a SaveChanges interceptor or before-save hook.
- Enable nullable reference types project-wide to catch null assignments at compile time.
When it happens
Trigger: Calling SaveChanges/SaveChangesAsync (or Add+Save) on a tracked entity where a required scalar property (IsNullable == false, e.g. configured via .IsRequired() or a non-nullable CLR type without C# nullable reference annotations) holds null. Also triggered by updating an existing entity to set a required property to null.
Common situations: Newly constructed entities where a required property was never set; JSON/DTO mapping that copies null across; switch from nullable to non-nullable CLR type without seeding data; migrations of existing documents that predate the IsRequired() configuration; DTO mappers using AutoMapper that skip unset fields.
Related errors
- The Cosmos database provider does not support transactions.
- Invalid token type: '{tokenType}'.
- When using AutoTransactionBehavior.Always with the Cosmos DB
- When using AutoTransactionBehavior.Always with the Cosmos DB
- The entity of type '{entityType}' is mapped as part of the d
AI-assisted analysis of dotnet/efcore@dbf9771522 (2026-08-06).
Data as JSON: /api/errors/1a4538f667119479.
Report an issue: GitHub.