Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for 21133. IndexAttribute properties did not have the right TypeMappings #21183

Merged
merged 3 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/EFCore/Metadata/Builders/IConventionEntityTypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,37 @@ IConventionServicePropertyBuilder ServiceProperty(
/// <returns> <see langword="true" /> if the entity type can be marked as keyless. </returns>
bool CanRemoveKey(bool fromDataAnnotation = false);

/// <summary>
/// Configures an index on the specified property names.
/// If there is an existing index on the given list of property names,
/// then the existing index will be returned for configuration.
/// </summary>
/// <param name="propertyNames"> The names of the properties that make up the index. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// An object that can be used to configure the index if it exists on the entity type,
/// <see langword="null" /> otherwise.
/// </returns>
IConventionIndexBuilder HasIndex(
[NotNull] IReadOnlyList<string> propertyNames, bool fromDataAnnotation = false);

/// <summary>
/// Configures an index on the specified property names.
/// If there is an existing index on the given list of properyt names,
/// then the existing index will be returned for configuration.
/// </summary>
/// <param name="propertyNames"> The names of the properties that make up the index. </param>
/// <param name="name"> The name of the index. </param>
/// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param>
/// <returns>
/// An object that can be used to configure the index if it exists on the entity type,
/// <see langword="null" /> otherwise.
/// </returns>
IConventionIndexBuilder HasIndex(
[NotNull] IReadOnlyList<string> propertyNames,
[NotNull] string name,
bool fromDataAnnotation = false);

/// <summary>
/// Configures an index on the specified properties.
/// If there is an existing index on the given list of properties,
Expand Down
213 changes: 150 additions & 63 deletions src/EFCore/Metadata/Conventions/IndexAttributeConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
Expand All @@ -16,7 +16,8 @@ namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
/// <summary>
/// A convention that configures database indexes based on the <see cref="IndexAttribute" />.
/// </summary>
public class IndexAttributeConvention : IModelFinalizingConvention
public class IndexAttributeConvention : IEntityTypeAddedConvention,
IEntityTypeBaseTypeChangedConvention, IModelFinalizingConvention
{
/// <summary>
/// Creates a new instance of <see cref="IndexAttributeConvention" />.
Expand All @@ -33,78 +34,164 @@ public IndexAttributeConvention([NotNull] ProviderConventionSetBuilderDependenci
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }

/// <inheritdoc/>
public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext<IConventionModelBuilder> context)
public virtual void ProcessEntityTypeAdded(
IConventionEntityTypeBuilder entityTypeBuilder,
IConventionContext<IConventionEntityTypeBuilder> context)
{
CheckIndexAttributesAndEnsureIndex(entityTypeBuilder.Metadata, false);
}

/// <inheritdoc/>
public virtual void ProcessEntityTypeBaseTypeChanged(
IConventionEntityTypeBuilder entityTypeBuilder,
IConventionEntityType newBaseType,
IConventionEntityType oldBaseType,
IConventionContext<IConventionEntityType> context)
{
if (oldBaseType == null)
{
return;
}

CheckIndexAttributesAndEnsureIndex(entityTypeBuilder.Metadata, false);
}

/// <inheritdoc/>
public virtual void ProcessModelFinalizing(
IConventionModelBuilder modelBuilder,
IConventionContext<IConventionModelBuilder> context)
{
foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
{
if (entityType.ClrType != null)
CheckIndexAttributesAndEnsureIndex(entityType, true);
}
}

private void CheckIndexAttributesAndEnsureIndex(
IConventionEntityType entityType,
bool shouldThrow)
{
if (entityType.ClrType == null)
{
return;
}

foreach (var indexAttribute in
entityType.ClrType.GetCustomAttributes<IndexAttribute>(true))
{
IConventionIndexBuilder indexBuilder = null;
if (!shouldThrow)
{
var ignoredMembers = entityType.GetIgnoredMembers();
foreach (var indexAttribute in
entityType.ClrType.GetCustomAttributes<IndexAttribute>(true))
var indexProperties = new List<IConventionProperty>();
foreach (var propertyName in indexAttribute.PropertyNames)
{
var indexProperties = new List<IConventionProperty>();
foreach (var propertyName in indexAttribute.PropertyNames)
var property = entityType.FindProperty(propertyName);
if (property == null)
{
if (ignoredMembers.Contains(propertyName))
{
if (indexAttribute.Name == null)
{
throw new InvalidOperationException(
CoreStrings.UnnamedIndexDefinedOnIgnoredProperty(
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName));
}
else
{
throw new InvalidOperationException(
CoreStrings.NamedIndexDefinedOnIgnoredProperty(
indexAttribute.Name,
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName));
}
}

var property = entityType.FindProperty(propertyName);
if (property == null)
{
if (indexAttribute.Name == null)
{
throw new InvalidOperationException(
CoreStrings.UnnamedIndexDefinedOnNonExistentProperty(
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName));
}
else
{
throw new InvalidOperationException(
CoreStrings.NamedIndexDefinedOnNonExistentProperty(
indexAttribute.Name,
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName));
}
}

indexProperties.Add(property);
return;
}

var indexBuilder = indexAttribute.Name == null
indexProperties.Add(property);
}

indexBuilder = indexAttribute.Name == null
? entityType.Builder.HasIndex(
indexProperties, fromDataAnnotation: true)
: entityType.Builder.HasIndex(
indexProperties, indexAttribute.Name, fromDataAnnotation: true);
}
else
{
// TODO See bug 21220 - we have to do this _before_ calling
// HasIndex() because during the call to HasIndex()
// IsIgnored (wrongly) returns false and we would end up
// creating a property where we shouldn't.
CheckIgnoredProperties(indexAttribute, entityType);

try
{
// Using the HasIndex(propertyNames) overload gives us
// a chance to create a missing property
// e.g. if the CLR property existed but was non-public.
indexBuilder = indexAttribute.Name == null
? entityType.Builder.HasIndex(
indexProperties, fromDataAnnotation: true)
indexAttribute.PropertyNames, fromDataAnnotation: true)
: entityType.Builder.HasIndex(
indexProperties, indexAttribute.Name, fromDataAnnotation: true);
indexAttribute.PropertyNames, indexAttribute.Name, fromDataAnnotation: true);
}
catch(InvalidOperationException exception)
{
CheckMissingProperties(indexAttribute, entityType, exception);

if (indexBuilder != null)
{
if (indexAttribute.GetIsUnique().HasValue)
{
indexBuilder.IsUnique(indexAttribute.GetIsUnique().Value, fromDataAnnotation: true);
}
}
throw;
}
}

if (indexBuilder != null
&& indexAttribute.GetIsUnique().HasValue)
{
indexBuilder.IsUnique(indexAttribute.GetIsUnique().Value, fromDataAnnotation: true);
}
}
}

private void CheckIgnoredProperties(
IndexAttribute indexAttribute,
IConventionEntityType entityType)
{
foreach (var propertyName in indexAttribute.PropertyNames)
{
if (entityType.IsIgnored(propertyName))
lajones marked this conversation as resolved.
Show resolved Hide resolved
{
if (indexAttribute.Name == null)
{
throw new InvalidOperationException(
CoreStrings.UnnamedIndexDefinedOnIgnoredProperty(
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName));
}
else
{
throw new InvalidOperationException(
CoreStrings.NamedIndexDefinedOnIgnoredProperty(
indexAttribute.Name,
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName));
}
}
}
}

private void CheckMissingProperties(
IndexAttribute indexAttribute,
IConventionEntityType entityType,
InvalidOperationException innerException)
{
foreach (var propertyName in indexAttribute.PropertyNames)
{
var property = entityType.FindProperty(propertyName);
if (property == null)
{
if (indexAttribute.Name == null)
{
throw new InvalidOperationException(
CoreStrings.UnnamedIndexDefinedOnNonExistentProperty(
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName),
innerException);
}
else
{
throw new InvalidOperationException(
CoreStrings.NamedIndexDefinedOnNonExistentProperty(
indexAttribute.Name,
entityType.DisplayName(),
indexAttribute.PropertyNames.Format(),
propertyName),
innerException);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public virtual ConventionSet CreateConventionSet()
var inversePropertyAttributeConvention = new InversePropertyAttributeConvention(Dependencies);
var relationshipDiscoveryConvention = new RelationshipDiscoveryConvention(Dependencies);
var servicePropertyDiscoveryConvention = new ServicePropertyDiscoveryConvention(Dependencies);
var indexAttributeConvention = new IndexAttributeConvention(Dependencies);

conventionSet.EntityTypeAddedConventions.Add(new NotMappedEntityTypeAttributeConvention(Dependencies));
conventionSet.EntityTypeAddedConventions.Add(new OwnedEntityTypeAttributeConvention(Dependencies));
Expand All @@ -70,6 +71,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.EntityTypeAddedConventions.Add(propertyDiscoveryConvention);
conventionSet.EntityTypeAddedConventions.Add(servicePropertyDiscoveryConvention);
conventionSet.EntityTypeAddedConventions.Add(keyDiscoveryConvention);
conventionSet.EntityTypeAddedConventions.Add(indexAttributeConvention);
conventionSet.EntityTypeAddedConventions.Add(inversePropertyAttributeConvention);
conventionSet.EntityTypeAddedConventions.Add(relationshipDiscoveryConvention);
conventionSet.EntityTypeAddedConventions.Add(new DerivedTypeDiscoveryConvention(Dependencies));
Expand All @@ -87,6 +89,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.EntityTypeBaseTypeChangedConventions.Add(propertyDiscoveryConvention);
conventionSet.EntityTypeBaseTypeChangedConventions.Add(servicePropertyDiscoveryConvention);
conventionSet.EntityTypeBaseTypeChangedConventions.Add(keyDiscoveryConvention);
conventionSet.EntityTypeBaseTypeChangedConventions.Add(indexAttributeConvention);
conventionSet.EntityTypeBaseTypeChangedConventions.Add(inversePropertyAttributeConvention);
conventionSet.EntityTypeBaseTypeChangedConventions.Add(relationshipDiscoveryConvention);
conventionSet.EntityTypeBaseTypeChangedConventions.Add(foreignKeyIndexConvention);
Expand Down Expand Up @@ -170,6 +173,7 @@ public virtual ConventionSet CreateConventionSet()

conventionSet.ModelFinalizingConventions.Add(new ModelCleanupConvention(Dependencies));
conventionSet.ModelFinalizingConventions.Add(keyAttributeConvention);
conventionSet.ModelFinalizingConventions.Add(indexAttributeConvention);
conventionSet.ModelFinalizingConventions.Add(foreignKeyAttributeConvention);
conventionSet.ModelFinalizingConventions.Add(new ChangeTrackingStrategyConvention(Dependencies));
conventionSet.ModelFinalizingConventions.Add(new ConstructorBindingConvention(Dependencies));
Expand All @@ -182,7 +186,6 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.ModelFinalizingConventions.Add(new QueryFilterDefiningQueryRewritingConvention(Dependencies));
conventionSet.ModelFinalizingConventions.Add(inversePropertyAttributeConvention);
conventionSet.ModelFinalizingConventions.Add(backingFieldConvention);
conventionSet.ModelFinalizingConventions.Add(new IndexAttributeConvention(Dependencies));

conventionSet.ModelFinalizedConventions.Add(new ValidatingConvention(Dependencies));

Expand Down
27 changes: 27 additions & 0 deletions src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4455,6 +4455,33 @@ IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoKey(IConventionKe
bool IConventionEntityTypeBuilder.CanRemoveKey(bool fromDataAnnotation)
=> CanRemoveKey(fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <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>
[DebuggerStepThrough]
IConventionIndexBuilder IConventionEntityTypeBuilder.HasIndex(
IReadOnlyList<string> propertyNames, bool fromDataAnnotation)
=> HasIndex(
propertyNames,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <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>
[DebuggerStepThrough]
IConventionIndexBuilder IConventionEntityTypeBuilder.HasIndex(
IReadOnlyList<string> propertyNames, string name, bool fromDataAnnotation)
=> HasIndex(
propertyNames,
name,
fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention);

/// <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
Loading