{"record":{"id":"52b01bea6cf0ddce","repo":"dotnet/efcore","slug":"an-error-occurred-while-reading-a-database-value-52b01b","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/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Relational/Extensions/RelationalPropertyExtensions.cs#L2030-L2066","documentation":"The fallback materialization error from ThrowReadValueException: thrown when the reader throws an exception that is neither NullReferenceException nor InvalidCastException and there is no bound IProperty (else branch). The original provider exception is preserved as InnerException. Indicates an arbitrary driver-level failure reading a value slot.","triggerScenarios":"Any non-cast, non-null exception from the ADO.NET provider while reading a projected value: a truncated fixed-length column, an encoding error on a national-character column, a deserialization failure on a JSON/JSONB column, or a network read timeout surfacing as a driver exception during value access.","commonSituations":"Truncated NVARCHAR columns; locale/encoding mismatches on character data; corrupt JSON column payloads; provider-specific deserialization bugs after a driver upgrade; transient network errors surfacing during a streaming read.","solutions":["Inspect the InnerException for the driver-specific error code and address its root cause (truncation, encoding, payload).","If transient (network/timeout), wrap the query execution in a retry policy (e.g. Polly with ExecuteDelete/ExecuteUpdate safe semantics).","Verify the column type and size against the data being stored; widen the column if truncated.","For JSON columns, validate payload shape before insert and check the provider's JSON reader version compatibility."],"exampleFix":"// before\nvar v = await db.Database.SqlQueryRaw<JsonObject>(\"SELECT payload FROM events\").FirstAsync();\n\n// after — read as string, parse defensively, surface inner exception for diagnosis\ntry {\n    var raw = await db.Database.SqlQueryRaw<string>(\"SELECT payload::text FROM events\").FirstAsync();\n    var v = JsonSerializer.Deserialize<JsonObject>(raw);\n} catch (InvalidOperationException ex) {\n    logger.LogError(ex.InnerException, \"driver-level read failure\");\n    throw;\n}","handlingStrategy":"try-catch","validationCode":"if (ex.InnerException is not null) logInner(ex.InnerException);","typeGuard":null,"tryCatchPattern":"try { var v = await query.ToListAsync(); }\ncatch (InvalidOperationException ex) when (ex.Message.StartsWith(\"An error occurred while reading a database value.\"))\n{\n    logger.LogError(ex.InnerException, \"Driver-level read failure\");\n    if (IsTransient(ex.InnerException)) await retry(policy, query);\n    else throw;\n}","preventionTips":["Always inspect InnerException for the real driver error code.","For streaming reads over flaky networks, use a retry policy around query execution.","Validate JSON column payloads before insert to avoid reader deserialization failures."],"tags":["materialization","driver-error","inner-exception","provider"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}