{"record":{"id":"9dd12f4f58bb0760","repo":"dotnet/efcore","slug":"an-error-occurred-while-reading-a-database-value-9dd12f","errorCode":null,"errorMessage":"An error occurred while reading a database value. The expected type was '{expectedType}' but the actual value was 'null'.","messagePattern":"An error occurred while reading a database value\\. The expected type was '(.+?)' but the actual value was 'null'\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Query/Internal/BufferedDataReader.cs","lineNumber":1934,"sourceCode":"\n                message = exception is NullReferenceException\n                    || Equals(value, DBNull.Value)\n                        ? RelationalStrings.ErrorMaterializingPropertyNullReference(entityType, propertyName, expectedType)\n                        : exception is InvalidCastException\n                            ? CoreStrings.ErrorMaterializingPropertyInvalidCast(entityType, propertyName, expectedType, actualType)\n                            : RelationalStrings.ErrorMaterializingProperty(entityType, propertyName);\n            }\n            else\n            {\n                message = exception is NullReferenceException\n                    || Equals(value, DBNull.Value)\n                        ? RelationalStrings.ErrorMaterializingValueNullReference(expectedType)\n                        : exception is InvalidCastException\n                            ? RelationalStrings.ErrorMaterializingValueInvalidCast(expectedType, actualType)\n                            : RelationalStrings.ErrorMaterializingValue;\n            }\n\n            throw new InvalidOperationException(message, exception);\n        }\n    }\n}\n","sourceCodeStart":1916,"sourceCodeEnd":1938,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs#L1916-L1938","documentation":"Materialization null mismatch: ThrowReadValueException reports 'expected type was X but the actual value was null' when the reader returns DBNull/null for a column whose expected CLR type is a non-nullable value type (after MakeNullable based on the column's nullability flag). EF treats this as a data integrity violation.","triggerScenarios":"A non-nullable value-type property receives a NULL from the database (column is NOT NULL in model but contains NULL in data, or the SQL/projection produced NULL); a computed/default column returning NULL for a non-nullable property; LEFT JOIN producing NULLs for a required value-type property.","commonSituations":"A NOT NULL column that actually has NULLs (data inconsistency); a LEFT JOIN feeding a struct property; a stored proc returning NULL for an int/DateTime/Guid property; default values not applied by the DB.","solutions":["Make the CLR property nullable (int? / DateTime?) so NULL materializes without error.","Ensure the column truly disallows NULL in the database and backfill existing NULLs.","If NULL comes from a JOIN, switch to an inner join or project into a nullable type.","Add a database DEFAULT / configure a value generator so the column is never NULL."],"exampleFix":"// before - non-nullable property, DB returns NULL\npublic DateTime CreatedAt { get; set; }\n\n// after - nullable property\npublic DateTime? CreatedAt { get; set; };","handlingStrategy":"validation","validationCode":"foreach (var et in dbContext.Model.GetEntityTypes())\nforeach (var p in et.GetProperties())\n    if (!p.IsNullable && p.ClrType.IsValueType)\n    {\n        // ensure the DB column is NOT NULL and has a default; check data for stray NULLs\n        var col = p.GetColumnName();\n        Console.WriteLine($\"Verify DB column {et.GetTableName()}.{col} has no NULLs for non-nullable property {p.Name}.\");\n    }","typeGuard":null,"tryCatchPattern":"try { return ctx.Set<T>().ToList(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"actual value was 'null'\"))\n{ _logger.LogError(ex, \"NULL read into non-nullable property; make property nullable or fix data.\"); throw; }","preventionTips":["Make CLR value-type properties nullable (int?) when the column may contain NULL.","Ensure NOT NULL columns have defaults and no stray NULLs.","Avoid LEFT JOINs feeding required value-type properties."],"tags":["efcore","query","materialization","null","nullable"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}