{"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/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Query/Internal/BufferedDataReader.cs#L1916-L1938","documentation":"Materialization type mismatch: ThrowReadValueException reports 'expected type was X but the actual value was of type Y' when the underlying GetFieldValue throws InvalidCastException because the database value's runtime type cannot be coerced into the shaper's expected CLR type. The expected and actual type names are included.","triggerScenarios":"A column returns a value of a type incompatible with the mapped property (e.g. DB returns string but property is int; provider returns long for an int property on some dialects); a value converter mismatch; enum stored as string but mapped as int without conversion.","commonSituations":"Enum stored as string in DB but property is the enum/int without HasConversion; JSON/JSONB returned as string but property is a typed object; provider returning a different numeric type (e.g. bigint for an int column); SQLite dynamic typing where a column holds an unexpected type.","solutions":["Add a HasConversion on the property to convert between the DB type and the CLR type (e.g. enum <-> string).","Change the CLR property type to match what the provider returns (e.g. long instead of int).","Fix the stored data / SQL so the column's type matches the model.","For SQLite dynamic typing, ensure stored values are of the expected type or use conversions."],"exampleFix":"// before - DB stores enum as string, property is enum (no conversion)\npublic OrderStatus Status { get; set; }\n\n// after - explicit conversion\nmodelBuilder.Entity<Order>()\n    .Property(o => o.Status)\n    .HasConversion<string>();","handlingStrategy":"validation","validationCode":"foreach (var et in dbContext.Model.GetEntityTypes())\nforeach (var p in et.GetProperties())\n    if (p.ClrType.IsEnum && p.GetValueConverter() == null && p.GetColumnType() is string s && s.Contains(\"char\"))\n        Console.WriteLine($\"{et}.{p.Name}: enum likely stored as string but has no conversion; add .HasConversion<string>().\");","typeGuard":null,"tryCatchPattern":"try { return ctx.Set<T>().ToList(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"expected type was\") && ex.Message.Contains(\"actual value was of type\"))\n{ _logger.LogError(ex, \"Type mismatch on materialization; add HasConversion or change CLR type.\"); throw; }","preventionTips":["Add HasConversion for enums and provider-specific numeric/string types.","Align CLR numeric types with the provider's returned types (e.g. long vs int).","For SQLite, normalize stored types to match the model."],"tags":["efcore","query","materialization","type-mismatch","invalid-cast"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}