{"record":{"id":"1a4538f667119479","repo":"dotnet/efcore","slug":"the-property-1-entitytype-0-property-contain","errorCode":null,"errorMessage":"The property '{1_entityType}.{0_property}' contains null, but the property is marked as required.  Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.","messagePattern":"The property '(.+?)\\.(.+?)' contains null, but the property is marked as required\\.  Consider using 'DbContextOptionsBuilder\\.EnableSensitiveDataLogging' to see the key values\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs","lineNumber":428,"sourceCode":"        {\n            if (!discriminatorProperty.IsShadowProperty())\n            {\n                return discriminatorProperty.GetGetter().GetClrValue(instance!);\n            }\n\n            var instanceType = instance!.GetType();\n            return structuralType.GetDerivedTypesInclusive().First(t => t.ClrType == instanceType).GetDiscriminatorValue();\n        }\n\n        public void SetOrdinal(IProperty ordinalKeyProperty, int? ordinal)\n        {\n        }\n\n        public void ValidateNull(IProperty property, ITypeBase structuralType)\n        {\n            if (!property.IsNullable)\n            {\n                throw new InvalidOperationException(CoreStrings.PropertyConceptualNull(property.Name, structuralType.DisplayName()));\n            }\n        }\n\n        public void ValidateNull(IComplexProperty complexProperty, ITypeBase structuralType)\n        {\n            if (!complexProperty.IsNullable)\n            {\n                throw new InvalidOperationException(CoreStrings.PropertyConceptualNull(complexProperty.Name, structuralType.DisplayName()));\n            }\n        }\n\n        public void ValidateNull(INavigation navigation, ITypeBase structuralType)\n        {\n            if (navigation.ForeignKey.IsRequired)\n            {\n                throw new InvalidOperationException(CoreStrings.PropertyConceptualNull(navigation.Name, structuralType.DisplayName()));\n            }\n        }","sourceCodeStart":410,"sourceCodeEnd":446,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Cosmos/Storage/Internal/CosmosStructuralTypeSerializer.cs#L410-L446","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nvar order = new Order { Id = 42 }; // RequiredProp never set\nctx.Add(order);\nawait ctx.SaveChangesAsync(); // throws PropertyConceptualNull on Order.RequiredProp\n\n// after\nvar order = new Order { Id = 42, RequiredProp = \"default\" };\n// or in OnModelCreating: modelBuilder.Entity<Order>().Property(o => o.RequiredProp).IsRequired(false);","handlingStrategy":"validation","validationCode":"// Validate required scalar properties before SaveChanges\nvar required = db.Model.FindEntityType(typeof(Order))!\n    .GetProperties()\n    .Where(p => !p.IsNullable)\n    .ToList();\nforeach (var entry in db.ChangeTracker.Entries<Order>())\n{\n    foreach (var p in required)\n    {\n        if (p.GetGetter().GetClrValue(entry.Entity) is null)\n            throw new InvalidOperationException($\"{entry.Entity.GetType().Name}.{p.Name} is required but null.\");\n    }\n}","typeGuard":"static bool HasAllRequiredScalars<TEntity>(TEntity entity, IModel model)\n{\n    var et = model.FindEntityType(typeof(TEntity));\n    if (et is null) return true;\n    foreach (var p in et.GetProperties().Where(p => !p.IsNullable))\n    {\n        if (p.GetGetter().GetClrValue(entity!) is null) return false;\n    }\n    return true;\n}","tryCatchPattern":"try\n{\n    await db.SaveChangesAsync(ct);\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"contains null, but the property is marked as required\"))\n{\n    // log, enable EnableSensitiveDataLogging to get the key, then surface a domain error\n    throw new DomainValidationException(\"A required property was null at save time.\", ex);\n}","preventionTips":["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."],"tags":["cosmos","serialization","required-property","null","savechanges","efcore"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}