{"record":{"id":"52b01bea6cf0ddce","repo":"dotnet/efcore","slug":"an-error-occurred-while-reading-a-database-value","errorCode":null,"errorMessage":"An error occurred while reading a database value. See the inner exception for more information.","messagePattern":"An error occurred while reading a database value\\. See the inner exception for more information\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs","lineNumber":2048,"sourceCode":"            message\n                = 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\n                = exception is NullReferenceException\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    /// <summary>\n    ///     Gets the value of JSON property name used for the given property of an entity mapped to a JSON column.\n    /// </summary>\n    /// <remarks>\n    ///     Unless configured explicitly, entity property name is used.\n    /// </remarks>\n    /// <param name=\"property\">The property.</param>\n    /// <returns>\n    ///     The value for the JSON property used to store the value of this entity property.\n    ///     By default <see langword=\"null\" /> is returned for key properties and for properties that\n    ///     are not mapped to JSON.\n    /// </returns>\n    public static string? GetJsonPropertyName(this IReadOnlyProperty property)\n        => (string?)property.FindAnnotation(RelationalAnnotationNames.JsonPropertyName)?.Value\n            ?? (property.IsKey() || !property.DeclaringType.IsMappedToJson()\n                ? null","sourceCodeStart":2030,"sourceCodeEnd":2066,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs#L2030-L2066","documentation":"Thrown by ThrowReadValueException in RelationalPropertyExtensions.cs:2048 while EF Core reads a column value out of a DbDataReader and materializes it into an entity/primitive. It wraps the real database/contractor exception (cast failure, null into non-nullable, DBNull, converter error) as its InnerException and re-throws as InvalidOperationException with a contextual message. The library does this so a raw ADO.NET failure is reported with the entity type and property name rather than an opaque cast.","triggerScenarios":"Executing a query whose materializer calls the compiled value reader and the underlying DbDataReader.GetX()/value converter throws. Concrete triggers: a NULL lands on a non-nullable value-type property; a column value cannot be cast to the configured CLR type (e.g. string column into int); a value converter throws in ConvertFromProvider; the reader returns a type incompatible with the providerClrType.","commonSituations":"Database schema drifted from the model (column type changed, new NOT NULL without default), a value converter whose provider type mismatches the column, nullable DB column mapped to a non-nullable CLR property, regional/encoding issues producing unparseable values, importing legacy data with empty strings/DBNull where a numeric is expected.","solutions":["Inspect the InnerException (and its message) - it names the exact cast/conversion failure; the EF message only adds entity/property context.","Compare the failing column's database type against the mapped CLR property (GetColumnType(), IsNullable) and reconcile the model or the schema with a migration.","If a value converter is involved, verify ConverterClrType/ProviderClrType align with both the CLR property and the DB column type.","Make the CLR property nullable (int?/DateTime?) if the column legitimately contains NULL, or add a database default/NOT NULL constraint with backfill.","For transient/bad rows, project through a Select that normalizes the value before materialization."],"exampleFix":"// before\npublic int StockCount { get; set; } // column is NULLABLE in DB -> NullReferenceException on read\n\n// after (option A: make nullable)\npublic int? StockCount { get; set; }\n\n// after (option B: ensure column NOT NULL with default)\n// modelBuilder.Entity<Product>().Property(p => p.StockCount).HasDefaultValue(0);","handlingStrategy":"try-catch","validationCode":"// Cannot fully validate pre-query; mitigate by checking nullability up front.\nforeach (var prop in context.Model.GetEntityTypes().SelectMany(e => e.GetProperties()))\n{\n    if (!prop.IsNullable && prop.GetColumnType() is { } col\n        && /* your schema metadata says column is nullable */ false)\n    {\n        // flag risk: non-nullable CLR property over a nullable column\n    }\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    var result = await query.ToListAsync();\n}\ncatch (InvalidOperationException ex)\n    when (ex.InnerException != null\n         && (ex.InnerException is InvalidCastException\n             || ex.InnerException is NullReferenceException\n             || ex.InnerException is FormatException))\n{\n    // ex.Message names the entity/property; ex.InnerException is the real cause.\n    logger.LogError(ex.InnerException, \"Materialization failed reading {Message}\", ex.Message);\n    throw new MyDomainReadException(\"Bad data in result set; see inner.\", ex.InnerException);\n}","preventionTips":["Keep the EF model and DB schema in lock-step via migrations so column nullability/types match.","Use nullable CLR types for columns that can be NULL.","Unit-test value converters with NULL, DBNull, and boundary values.","Log the InnerException whenever you surface materialization errors."],"tags":["materialization","value-converter","schema-mismatch","runtime"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}