Skip to content

Commit

Permalink
Improve the relationship cycle breaking logic to detect cycles even w…
Browse files Browse the repository at this point in the history
…hen not starting on one. (#32598)

Additionally, detect multiple relationship chains that end with incompatible conversions.

Fixes #32422
  • Loading branch information
AndriySvyryd authored Jan 4, 2024
1 parent 08da61e commit 119c872
Show file tree
Hide file tree
Showing 7 changed files with 436 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,12 @@ private void Create(
return (Type?)annotation.Value;
}

if (!Property.UseOldBehavior32422)
{
return ((Property)property).GetConversion(throwOnProviderClrTypeConflict: false, throwOnValueConverterConflict: false)
.ValueConverterType;
}

var principalProperty = property;
var i = 0;
for (; i < ForeignKey.LongestFkChainAllowedLength; i++)
Expand Down
229 changes: 229 additions & 0 deletions src/EFCore/Metadata/Internal/Property.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ public class Property : PropertyBase, IMutableProperty, IConventionProperty, IPr
private ConfigurationSource? _valueGeneratedConfigurationSource;
private ConfigurationSource? _typeMappingConfigurationSource;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static readonly bool UseOldBehavior32422 =
AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue32422", out var enabled32422) && enabled32422;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down Expand Up @@ -744,6 +753,12 @@ private object? DefaultSentinel
return (ValueConverter?)annotation.Value;
}

if (!UseOldBehavior32422)
{
return GetConversion(throwOnProviderClrTypeConflict: FindAnnotation(CoreAnnotationNames.ProviderClrType) == null)
.ValueConverter;
}

var property = this;
var i = 0;
for (; i < ForeignKey.LongestFkChainAllowedLength; i++)
Expand Down Expand Up @@ -836,6 +851,12 @@ private object? DefaultSentinel
return (Type?)annotation.Value;
}

if (!UseOldBehavior32422)
{
return GetConversion(throwOnValueConverterConflict: FindAnnotation(CoreAnnotationNames.ValueConverter) == null)
.ProviderClrType;
}

var property = this;
var i = 0;
for (; i < ForeignKey.LongestFkChainAllowedLength; i++)
Expand Down Expand Up @@ -880,6 +901,214 @@ private object? DefaultSentinel
: null;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual (ValueConverter? ValueConverter, Type? ValueConverterType, Type? ProviderClrType) GetConversion(
bool throwOnValueConverterConflict = true,
bool throwOnProviderClrTypeConflict = true)
{
Queue<(Property CurrentProperty, Property CycleBreakingPropert, int CyclePosition, int MaxCycleLength)>? queue = null;
(Property CurrentProperty, Property CycleBreakingPropert, int CyclePosition, int MaxCycleLength)? currentNode =
(this, this, 0, 2);

ValueConverter? valueConverter = null;
Type? valueConverterType = null;
Type? providerClrType = null;
while (currentNode is not null || queue is { Count: > 0 })
{
var (property, cycleBreakingProperty, cyclePosition, maxCycleLength) = currentNode ?? queue!.Dequeue();
currentNode = null;
if (cyclePosition >= ForeignKey.LongestFkChainAllowedLength)
{
throw new InvalidOperationException(
CoreStrings.RelationshipCycle(DeclaringType.DisplayName(), Name, "ValueConverter"));
}

foreach (var foreignKey in property.GetContainingForeignKeys())
{
for (var propertyIndex = 0; propertyIndex < foreignKey.Properties.Count; propertyIndex++)
{
if (property != foreignKey.Properties[propertyIndex])
{
continue;
}

var principalProperty = foreignKey.PrincipalKey.Properties[propertyIndex];
if (principalProperty == cycleBreakingProperty)
{
break;
}

var annotationFound = GetConversion(
principalProperty,
throwOnValueConverterConflict,
throwOnProviderClrTypeConflict,
ref valueConverter,
ref valueConverterType,
ref providerClrType);
if (!annotationFound)
{
if (currentNode != null)
{
queue = new();
queue.Enqueue(currentNode.Value);
}

if (cyclePosition == maxCycleLength - 1)
{
// We need to use different primes to ensure a different cycleBreakingProperty is selected
// each time when traversing properties that participate in multiple relationship cycles
currentNode = (principalProperty, property, 0, HashHelpers.GetPrime(maxCycleLength << 1));
}
else
{
currentNode = (principalProperty, cycleBreakingProperty, cyclePosition + 1, maxCycleLength);
}

if (queue != null)
{
queue.Enqueue(currentNode.Value);
currentNode = null;
}
}
break;
}
}
}

return (valueConverter, valueConverterType, providerClrType);

bool GetConversion(
Property principalProperty,
bool throwOnValueConverterConflict,
bool throwOnProviderClrTypeConflict,
ref ValueConverter? valueConverter,
ref Type? valueConverterType,
ref Type? providerClrType)
{
var annotationFound = false;
var valueConverterAnnotation = principalProperty.FindAnnotation(CoreAnnotationNames.ValueConverter);
if (valueConverterAnnotation != null)
{
var annotationValue = (ValueConverter?)valueConverterAnnotation.Value;
if (annotationValue != null)
{
if (valueConverter != null
&& annotationValue.GetType() != valueConverter.GetType())
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
valueConverter.GetType().ShortDisplayName(), annotationValue.GetType().ShortDisplayName()));
}

if (valueConverterType != null
&& annotationValue.GetType() != valueConverterType)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
valueConverterType.ShortDisplayName(), annotationValue.GetType().ShortDisplayName()));
}

if (providerClrType != null
&& throwOnProviderClrTypeConflict)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
providerClrType.ShortDisplayName(), annotationValue.GetType().ShortDisplayName()));
}

valueConverter = annotationValue;
}
annotationFound = true;
}

var valueConverterTypeAnnotation = principalProperty.FindAnnotation(CoreAnnotationNames.ValueConverterType);
if (valueConverterTypeAnnotation != null)
{
var annotationValue = (Type?)valueConverterTypeAnnotation.Value;
if (annotationValue != null)
{
if (valueConverter != null
&& valueConverter.GetType() != annotationValue)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
valueConverter.GetType().ShortDisplayName(), annotationValue.ShortDisplayName()));
}

if (valueConverterType != null
&& valueConverterType != annotationValue)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
valueConverterType.ShortDisplayName(), annotationValue.ShortDisplayName()));
}

if (providerClrType != null
&& throwOnProviderClrTypeConflict)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
providerClrType.ShortDisplayName(), annotationValue.ShortDisplayName()));
}

valueConverterType = annotationValue;
}
annotationFound = true;
}

var providerClrTypeAnnotation = principalProperty.FindAnnotation(CoreAnnotationNames.ProviderClrType);
if (providerClrTypeAnnotation != null)
{
var annotationValue = (Type?)providerClrTypeAnnotation.Value;
if (annotationValue != null)
{
if (providerClrType != null
&& annotationValue != providerClrType)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
providerClrType.ShortDisplayName(), annotationValue.ShortDisplayName()));
}

if (valueConverter != null
&& throwOnValueConverterConflict)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
valueConverter.GetType().ShortDisplayName(), annotationValue.ShortDisplayName()));
}

if (valueConverterType != null
&& throwOnValueConverterConflict)
{
throw new InvalidOperationException(
CoreStrings.ConflictingRelationshipConversions(
DeclaringType.DisplayName(), Name,
valueConverterType.ShortDisplayName(), annotationValue.ShortDisplayName()));
}

providerClrType = annotationValue;
}
annotationFound = true;
}

return annotationFound;
}
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
9 changes: 9 additions & 0 deletions src/EFCore/Properties/CoreStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/EFCore/Properties/CoreStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,9 @@
<data name="ConflictingPropertyOrNavigation" xml:space="preserve">
<value>The property or navigation '{member}' cannot be added to the '{type}' type because a property or navigation with the same name already exists on the '{conflictingType}' type.</value>
</data>
<data name="ConflictingRelationshipConversions" xml:space="preserve">
<value>The property '{entityType}.{property}' participates in several relationship chains that have conflicting conversions: '{valueConversion}' and '{conflictingValueConversion}'.</value>
</data>
<data name="ConflictingRelationshipNavigation" xml:space="preserve">
<value>Cannot create a relationship between '{newPrincipalNavigationSpecification}' and '{newDependentNavigationSpecification}' because a relationship already exists between '{existingPrincipalNavigationSpecification}' and '{existingDependentNavigationSpecification}'. Navigations can only participate in a single relationship. If you want to override an existing relationship call 'Ignore' on the navigation '{newDependentNavigationSpecification}' first in 'OnModelCreating'.</value>
</data>
Expand Down
Loading

0 comments on commit 119c872

Please sign in to comment.