{"record":{"id":"7247eede7ec9f0fe","repo":"dotnet/efcore","slug":"invalid-token-type-tokentype-7247ee","errorCode":null,"errorMessage":"Invalid token type: '{tokenType}'.","messagePattern":"Invalid token type: '(.+?)'\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs","lineNumber":330,"sourceCode":"    public sealed class CosmosJsonStringKeyedDictionaryReaderWriter<TElement>(JsonValueReaderWriter elementReaderWriter)\n        : JsonValueReaderWriter<IEnumerable<KeyValuePair<string, TElement>>>, ICompositeJsonValueReaderWriter\n#pragma warning restore EF1001\n    {\n        private readonly JsonValueReaderWriter<TElement> _elementReaderWriter = (JsonValueReaderWriter<TElement>)elementReaderWriter;\n\n        /// <summary>\n        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n        ///     any release. You should only use it directly in your code with extreme caution and knowing that\n        ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n        /// </summary>\n        public override IEnumerable<KeyValuePair<string, TElement>> FromJsonTyped(\n            ref Utf8JsonReaderManager manager,\n            object? existingObject = null)\n        {\n            if (manager.CurrentReader.TokenType != JsonTokenType.StartObject)\n            {\n                throw new InvalidOperationException(CoreStrings.JsonReaderInvalidTokenType(manager.CurrentReader.TokenType));\n            }\n\n            var dictionary = new Dictionary<string, TElement>();\n            while (true)\n            {\n                switch (manager.MoveNext())\n                {\n                    case JsonTokenType.PropertyName:\n                        var key = manager.CurrentReader.GetString()!;\n                        manager.MoveNext();\n                        dictionary.Add(key, _elementReaderWriter.FromJsonTyped(ref manager));\n                        break;\n                    case JsonTokenType.EndObject:\n                        return dictionary;\n                    default:\n                        throw new InvalidOperationException(CoreStrings.JsonReaderInvalidTokenType(manager.CurrentReader.TokenType));\n                }\n            }","sourceCodeStart":312,"sourceCodeEnd":348,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Cosmos/Storage/Internal/CosmosTypeMappingSource.cs#L312-L348","documentation":"Thrown by CosmosJsonStringKeyedDictionaryReaderWriter<TElement>.FromJsonTyped when the JSON reader is not positioned on a StartObject token while deserializing a Dictionary<string,TElement> from a Cosmos document. Cosmos stores dictionaries as JSON objects; if the stored JSON value is an array, primitive, or the reader is mispositioned, the token type is rejected (CoreStrings.JsonReaderInvalidTokenType).","triggerScenarios":"Reading a Cosmos document whose serialized dictionary property is not a JSON object (e.g. it is a JSON array or string); corrupt or hand-edited documents; schema drift where a property changed type between versions; partial/malformed JSON returned from a stored procedure.","commonSituations":"Documents written by a different serializer or older app version; manual edits in the Azure portal; migration tooling that wrote arrays instead of objects; mismatched model (property declared as Dictionary but document contains an array of pairs).","solutions":["Inspect the stored JSON document (Azure portal / Data Explorer) and correct the value to be a JSON object.","Align the CLR model with the stored shape: if the document stores an array, change the CLR type to a collection, not a Dictionary.","Run a migration to rewrite malformed documents into the expected object shape.","Ensure all writers use EF Core SaveChanges (consistent serialization) rather than external tools that produce different shapes."],"exampleFix":"// before: document stored as\n// { \"Tags\": [ {\"k\":\"a\",\"v\":1}, {\"k\":\"b\",\"v\":2} ] }\n// with model: public Dictionary<string,int> Tags { get; set; }\n// -> throws JsonReaderInvalidTokenType (array, not object)\n\n// after: store as object\n// { \"Tags\": { \"a\": 1, \"b\": 2 } }\n// or change model to match: public List<KeyValuePair<string,int>> Tags { get; set; }","handlingStrategy":"try-catch","validationCode":"// Validate the raw JSON shape before mapping\nvar raw = await container.ReadItemAsync<JToken>(id, new PartitionKey(pk));\nif (raw.Resource[propertyName] is JObject) { /* ok: object */ }\nelse { throw new SchemaException($\"{propertyName} must be a JSON object.\"); }","typeGuard":"bool IsJsonObject(JToken token) => token is JObject;\n// for System.Text.Json:\n// bool IsJsonObject(ref Utf8JsonReader r) => r.TokenType == JsonTokenType.StartObject;","tryCatchPattern":"try { var entity = await db.Set<MyEntity>().FindAsync(id); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Invalid token type\"))\n{\n    // schema mismatch in stored document; surface as a data-integrity error and log the document id\n    throw new DataIntegrityException($\"Document {id} has an unexpected JSON shape for a dictionary property.\", ex);\n}","preventionTips":["Inspect stored documents in Data Explorer before relying on a Dictionary mapping.","Write documents only through EF Core to keep serialization consistent.","Run a one-time schema validation pass after migrations.","Pin a single serializer/config for dictionary properties across versions."],"tags":["cosmos","json","serialization","dictionary","deserialization","schema-mismatch","efcore"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}