Fix NullReferenceException in CommandBatchPreparer.FormatValues hiding circular dependency errors #36507
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When Entity Framework Core encounters circular dependencies during
SaveChanges(), it attempts to generate a helpful error message that includes details about the entities involved. However, when sensitive data logging is enabled, aNullReferenceExceptioncan occur in theCommandBatchPreparer.FormatValuesmethod, which hides the actual circular dependency error from users.The issue occurs because the
FormatValuesmethod assumes thevaluesparameter is never null, but in certain edge cases (particularly with circular dependencies), the value factory methods (CreateDependentKeyValue,CreateKeyValue,CreateIndexValue) can return null. When this happens, accessingvalues[i]throws aNullReferenceExceptionthat masks the real error.Example of the problem:
Before this fix, users would see:
After this fix, users will see the actual error:
Solution:
Added a null check for the
valuesparameter in theFormatValuesmethod. Whenvaluesis null, the method now outputs "NULL" for each column instead of attempting to access the array, allowing the real circular dependency error to be properly displayed to users.The fix is minimal and surgical - it only adds a null check without changing any existing behavior when values is non-null.
Fixes #35665.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.