{"record":{"id":"5b0cf0582713b173","repo":"dotnet/efcore","slug":"an-error-occurred-while-reading-a-database-value-5b0cf0","errorCode":null,"errorMessage":"An error occurred while reading a database value. The expected type was '{expectedType}' but the actual value was of type '{actualType}'.","messagePattern":"An error occurred while reading a database value\\. The expected type was '(.+?)' but the actual value was of type '(.+?)'\\.","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/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs#L1916-L1938","documentation":"Thrown by BufferedDataReader.ThrowReadValueException when the database value cannot be cast to the mapped CLR type (InvalidCastException). The message reports both the expected CLR type and the actual runtime type of the value.","triggerScenarios":"A column's runtime type diverges from the property's CLR type so GetFieldValue throws InvalidCastException; ThrowReadValueException wraps it with ErrorMaterializingValueInvalidCast. E.g. DB returns string but property is int, or returns long for an int property.","commonSituations":"Schema/model drift: column type changed in DB but not in model. Provider returning a wider type (long vs int, decimal vs double). Implicit conversion gap between database type and CLR type. Stale model after a manual ALTER TABLE. Collation/encoding changes returning byte[] vs string.","solutions":["Align the property's CLR type with the actual database column type (e.g. long instead of int).","Add a value converter if the schema cannot change: .HasConversion<long>(v => v, v => checked((int)v)).","Update the model from the database (Scaffold-DbContext / dotnet ef dbcontext scaffold) to refresh types.","Check for provider type-mapping overrides or explicit .HasColumnType that conflict with the column."],"exampleFix":"// before\npublic class User\n{\n    public int Id { get; set; } // DB column is bigint\n}\n\n// after\npublic class User\n{\n    public long Id { get; set; }\n}","handlingStrategy":"validation","validationCode":"static void EnsureClrTypeMatchesStoreType(IProperty property, string storeType)\n{\n    var expected = property.GetValueConverter()?.ProviderClrType ?? property.ClrType;\n    // cross-check expected against the database column type via provider mapping\n    if (storeType.StartsWith(\"bigint\") && expected != typeof(long))\n        throw new InvalidOperationException($\"Property {property.Name} ({expected}) mismatches store type {storeType}.\");\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Keep the model in sync with the database schema (re-scaffold after DDL changes).","Use value converters for unavoidable type gaps.","Verify provider type mappings for edge types (decimal scale, enums)."],"tags":["ef-core","query","materialization","type-mismatch"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}