Entity Framework Core Exception when Querying JSON Objects with an ID Column
The Entity Framework Core 7 release saw the addition support for storing entities in a JSON format, without having to use serializers. This can be useful for a variety of situations, especially when data will only be retrieved as a single set.
The Exception
While using this feature I recently, I received the following exception message when attempting to execute an Entity Framework query.
System.Collections.Generic.KeyNotFoundException: The given key 'Property: OrderLine.Id (int) Required PK AfterSave:Throw ValueGenerated.OnAdd' was not present in the dictionary.
I thought this was odd, as the Id
property definitely had a value in the JSON object. I also wasn’t attempting to add or remove entities, just query existing ones.
After removing the majority of the query and reducing its complexity to just retrieving the first entity, I received the following exception when attempting to run the Entity Framework query.
Error creating query string: Expression of type 'System.Object' cannot be used for assignment to type 'System.Int32'.
This exception still seemed odd to me as I wasn’t attempting this assignment myself, so it must have been something within Entity Framework Core.
The Workaround
After a fair amount of searching the web, I finally stumbled upon a GitHub issue showing a System.ArgumentException during materialisation with a JSON object. The discussion in the issue showed that the Id
column is used as a key to allow Entity Framework Core to track the object.
At the moment, there doesn’t seem to be a fix for this issue, but there is a workaround. The Id
property can be renamed so that it no longer creates a conflict. If you need your stored JSON object to still have an Id
property, you can use the HasJsonPropertyName("Id")
property configuration to map this correctly.