Skip to content
Open
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
2 changes: 2 additions & 0 deletions EFCore.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<Project Path="test/EFCore.AspNet.InMemory.FunctionalTests/EFCore.AspNet.InMemory.FunctionalTests.csproj" />
<Project Path="test/EFCore.AspNet.Specification.Tests/EFCore.AspNet.Specification.Tests.csproj" />
<Project Path="test/EFCore.AspNet.Sqlite.FunctionalTests/EFCore.AspNet.Sqlite.FunctionalTests.csproj" />
<Project Path="test/EFCore.AspNet.SqlServer.FunctionalTests/EFCore.AspNet.SqlServer.FunctionalTests.csproj" />
<Project Path="test/EFCore.Cosmos.FunctionalTests/EFCore.Cosmos.FunctionalTests.csproj" />
<Project Path="test/EFCore.Cosmos.Tests/EFCore.Cosmos.Tests.csproj" />
<Project Path="test/EFCore.FSharp.FunctionalTests/EFCore.FSharp.FunctionalTests.fsproj" />
Expand All @@ -70,6 +71,7 @@
<Project Path="test/EFCore.Specification.Tests/EFCore.Specification.Tests.csproj" />
<Project Path="test/EFCore.Sqlite.FunctionalTests/EFCore.Sqlite.FunctionalTests.csproj" />
<Project Path="test/EFCore.Sqlite.Tests/EFCore.Sqlite.Tests.csproj" />
<Project Path="test/EFCore.SqlServer.HierarchyId.Tests/EFCore.SqlServer.HierarchyId.Tests.csproj" />
<Project Path="test/EFCore.Tests/EFCore.Tests.csproj" />
<Project Path="test/EFCore.VisualBasic.FunctionalTests/EFCore.VisualBasic.FunctionalTests.vbproj" />
<Project Path="test/Microsoft.Data.Sqlite.Tests/Microsoft.Data.Sqlite.sqlite3.Tests.csproj" />
Expand Down
63 changes: 62 additions & 1 deletion src/EFCore.Design/Migrations/Design/CSharpSnapshotGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Text;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
Expand Down Expand Up @@ -830,7 +831,10 @@ protected virtual void GenerateIndex(
// Note - method names below are meant to be hard-coded
// because old snapshot files will fail if they are changed

var indexProperties = string.Join(", ", index.Properties.Select(p => Code.Literal(p.Name)));
var collectionIndices = index.CollectionIndices;
var indexProperties = string.Join(
", ",
index.Properties.Select((p, i) => Code.Literal(BuildIndexPropertyPath(p, collectionIndices?[i]))));
var indexBuilderName = $"{entityTypeBuilderName}.HasIndex("
+ (index.Name is null
? indexProperties
Expand Down Expand Up @@ -863,6 +867,63 @@ protected virtual void GenerateIndex(
GenerateIndexAnnotations(indexBuilderName, index, stringBuilder);
}

private static string BuildIndexPropertyPath(IPropertyBase property, IReadOnlyList<int?>? collectionIndices)
{
// Fast path: a scalar declared directly on the entity has no brackets in any form.
if (property.DeclaringType is IEntityType
&& property is not IComplexProperty { IsCollection: true })
{
return property.Name;
}

// Build the path leaf-first, walking up through enclosing complex types. Each
// collection-traversal step (including the leaf when the leaf itself is a complex collection)
// consumes one entry from CollectionIndices, in reverse order.
var segments = new List<string>();
var collectionSegmentIndex = (collectionIndices?.Count ?? 0) - 1;

// The indexed leaf may itself be a complex collection (e.g. "Posts[]" / "Posts[3]").
segments.Add(BuildSegment(
property.Name,
property is IComplexProperty { IsCollection: true },
collectionIndices,
ref collectionSegmentIndex));

var declaringType = property.DeclaringType;
while (declaringType is IComplexType complexType)
{
var complexProperty = complexType.ComplexProperty;
segments.Add(BuildSegment(
complexProperty.Name,
complexProperty.IsCollection,
collectionIndices,
ref collectionSegmentIndex));

declaringType = complexProperty.DeclaringType;
}

segments.Reverse();
return string.Join(".", segments);

static string BuildSegment(
string name,
bool collection,
IReadOnlyList<int?>? collectionIndices,
ref int collectionSegmentIndex)
{
if (!collection)
{
return name;
}

var indexEntry = collectionIndices?[collectionSegmentIndex];
collectionSegmentIndex--;
return name + (indexEntry is null
? "[]"
: "[" + indexEntry.Value.ToString(CultureInfo.InvariantCulture) + "]");
}
}

/// <summary>
/// Generates code for the annotations on an index.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
Expand Down Expand Up @@ -2142,6 +2143,43 @@ private void Create(
mainBuilder.AppendLine();
}

private static void CollectionIndicesLiteral(
IndentedStringBuilder mainBuilder,
IReadOnlyList<IReadOnlyList<int?>?> collectionIndices)
{
mainBuilder.Append("[");
for (var i = 0; i < collectionIndices.Count; i++)
{
if (i > 0)
{
mainBuilder.Append(", ");
}

var entry = collectionIndices[i];
if (entry is null)
{
mainBuilder.Append("null");
continue;
}

mainBuilder.Append("[");
for (var j = 0; j < entry.Count; j++)
{
if (j > 0)
{
mainBuilder.Append(", ");
}

var value = entry[j];
mainBuilder.Append(value is null ? "null" : value.Value.ToString(CultureInfo.InvariantCulture));
}

mainBuilder.Append("]");
}

mainBuilder.Append("]");
}

private void Create(
IIndex index,
CSharpRuntimeAnnotationCodeGeneratorParameters parameters,
Expand Down Expand Up @@ -2170,6 +2208,13 @@ private void Create(
.Append(_code.Literal(true));
}

if (index.CollectionIndices is { } collectionIndices)
{
mainBuilder.AppendLine(",")
.Append("collectionIndices: ");
CollectionIndicesLiteral(mainBuilder, collectionIndices);
}

mainBuilder
.AppendLine(");")
.DecrementIndent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1288,7 +1288,11 @@ private void Create(
/// <param name="index">The unique constraint to which the annotations are applied.</param>
/// <param name="parameters">Additional parameters used during code generation.</param>
public virtual void Generate(ITableIndex index, CSharpRuntimeAnnotationCodeGeneratorParameters parameters)
=> GenerateSimpleAnnotations(parameters);
{
var annotations = parameters.Annotations;
annotations.Remove(RelationalAnnotationNames.JsonIndex);
GenerateSimpleAnnotations(parameters);
}

private void Create(
IForeignKeyConstraint foreignKey,
Expand Down Expand Up @@ -2449,6 +2453,10 @@ public override void Generate(IIndex index, CSharpRuntimeAnnotationCodeGenerator
{
parameters.Annotations.Remove(RelationalAnnotationNames.TableIndexMappings);
}
else
{
parameters.Annotations.Remove(RelationalAnnotationNames.JsonIndex);
}

base.Generate(index, parameters);
}
Expand Down
63 changes: 60 additions & 3 deletions src/EFCore.Relational/EFCore.Relational.baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -9985,6 +9985,14 @@
"Member": "const string JsonElementMappings",
"Value": "Relational:JsonElementMappings"
},
{
"Member": "const string JsonIndex",
"Value": "Relational:JsonIndex"
},
{
"Member": "const string JsonIndexPaths",
"Value": "Relational:JsonIndexPaths"
},
{
"Member": "const string JsonPropertyName",
"Value": "Relational:JsonPropertyName"
Expand Down Expand Up @@ -10134,6 +10142,9 @@
{
"Member": "RelationalAnnotationProvider(Microsoft.EntityFrameworkCore.Metadata.RelationalAnnotationProviderDependencies dependencies);"
},
{
"Member": "static Microsoft.EntityFrameworkCore.Metadata.IRelationalJsonElement FindJsonElement(Microsoft.EntityFrameworkCore.Metadata.IPropertyBase property, Microsoft.EntityFrameworkCore.Metadata.ITable table);"
},
{
"Member": "virtual System.Collections.Generic.IEnumerable<Microsoft.EntityFrameworkCore.Infrastructure.IAnnotation> For(Microsoft.EntityFrameworkCore.Metadata.IRelationalModel model, bool designTime);"
},
Expand Down Expand Up @@ -10190,6 +10201,12 @@
},
{
"Member": "virtual System.Collections.Generic.IEnumerable<Microsoft.EntityFrameworkCore.Infrastructure.IAnnotation> For(Microsoft.EntityFrameworkCore.Metadata.ITrigger trigger, bool designTime);"
},
{
"Member": "virtual bool IsJsonIndex(Microsoft.EntityFrameworkCore.Metadata.IIndex index);"
},
{
"Member": "virtual Microsoft.EntityFrameworkCore.Metadata.RelationalJsonIndex? TryBuildJsonIndex(Microsoft.EntityFrameworkCore.Metadata.ITableIndex index);"
}
],
"Properties": [
Expand Down Expand Up @@ -13128,6 +13145,31 @@
}
]
},
{
"Type": "sealed class Microsoft.EntityFrameworkCore.Metadata.RelationalJsonIndex : System.IEquatable<Microsoft.EntityFrameworkCore.Metadata.RelationalJsonIndex>",
"Methods": [
{
"Member": "RelationalJsonIndex(System.Collections.Generic.IReadOnlyList<Microsoft.EntityFrameworkCore.Metadata.IRelationalJsonElement> elements, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.IReadOnlyList<int?>?>? collectionIndices);"
},
{
"Member": "bool Equals(Microsoft.EntityFrameworkCore.Metadata.RelationalJsonIndex? other);"
},
{
"Member": "override bool Equals(object? obj);"
},
{
"Member": "override int GetHashCode();"
}
],
"Properties": [
{
"Member": "System.Collections.Generic.IReadOnlyList<System.Collections.Generic.IReadOnlyList<int?>?>? CollectionIndices { get; }"
},
{
"Member": "System.Collections.Generic.IReadOnlyList<Microsoft.EntityFrameworkCore.Metadata.IRelationalJsonElement> Elements { get; }"
}
]
},
{
"Type": "static class Microsoft.EntityFrameworkCore.RelationalKeyBuilderExtensions",
"Methods": [
Expand Down Expand Up @@ -14117,6 +14159,9 @@
{
"Member": "override void ValidateIndexOnComplexProperty(Microsoft.EntityFrameworkCore.Metadata.IIndex index, System.Collections.Generic.IReadOnlyList<Microsoft.EntityFrameworkCore.Metadata.IComplexProperty> complexProperties, Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger<Microsoft.EntityFrameworkCore.DbLoggerCategory.Model.Validation> logger);"
},
{
"Member": "override void ValidateIndexProperty(Microsoft.EntityFrameworkCore.Metadata.IIndex index, Microsoft.EntityFrameworkCore.Metadata.IPropertyBase property, Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger<Microsoft.EntityFrameworkCore.DbLoggerCategory.Model.Validation> logger);"
},
{
"Member": "virtual void ValidateIndexPropertyMapping(Microsoft.EntityFrameworkCore.Metadata.IIndex index, Microsoft.EntityFrameworkCore.Diagnostics.IDiagnosticsLogger<Microsoft.EntityFrameworkCore.DbLoggerCategory.Model.Validation> logger);"
},
Expand Down Expand Up @@ -16561,6 +16606,15 @@
{
"Member": "static string JsonObjectWithMultiplePropertiesMappedToSameJsonProperty(object? property1, object? property2, object? type, object? jsonPropertyName);"
},
{
"Member": "static string JsonPathIndexElementsCollectionIndicesMismatch(object? elementCount, object? collectionIndicesCount);"
},
{
"Member": "static string JsonPathIndexPropertiesInDifferentJsonColumns(object? indexProperties, object? entityType, object? firstColumn, object? secondColumn);"
},
{
"Member": "static string JsonPathIndexPropertyMissingJsonColumn(object? indexProperties, object? entityType, object? property);"
},
{
"Member": "static string JsonProjectingCollectionElementAccessedUsingParmeterNoTrackingWithIdentityResolution(object? entityTypeName, object? asNoTrackingWithIdentityResolution);"
},
Expand Down Expand Up @@ -19904,18 +19958,21 @@
"Type": "class Microsoft.EntityFrameworkCore.Infrastructure.StructuredJsonPath",
"Methods": [
{
"Member": "StructuredJsonPath(System.Collections.Generic.IReadOnlyList<Microsoft.EntityFrameworkCore.Metadata.StructuredJsonPathSegment> segments, int[] indices);"
"Member": "StructuredJsonPath(System.Collections.Generic.IReadOnlyList<Microsoft.EntityFrameworkCore.Metadata.StructuredJsonPathSegment> segments, System.Collections.Generic.IReadOnlyList<int?>? indices);"
},
{
"Member": "virtual System.Text.StringBuilder AppendTo(System.Text.StringBuilder builder, bool useAsteriskForNullIndex = true);"
},
{
"Member": "virtual System.Text.StringBuilder AppendTo(System.Text.StringBuilder builder);"
"Member": "virtual string ToString(bool useAsteriskForNullIndex = true);"
},
Comment thread
AndriySvyryd marked this conversation as resolved.
{
"Member": "override string ToString();"
}
],
"Properties": [
{
"Member": "virtual int[] Indices { get; }"
"Member": "virtual System.Collections.Generic.IReadOnlyList<int?>? Indices { get; }"
},
{
"Member": "virtual bool IsRoot { get; }"
Expand Down
56 changes: 54 additions & 2 deletions src/EFCore.Relational/Extensions/RelationalIndexExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ public static class RelationalIndexExtensions
return null;
}

var nameSegments = GetJsonPathNames(index) ?? columnNames;
var baseName = new StringBuilder()
.Append("IX_")
.Append(tableName)
.Append('_')
.AppendJoin(columnNames, "_")
.AppendJoin(nameSegments, "_")
.ToString();

return Uniquifier.Truncate(baseName, index.DeclaringEntityType.Model.GetMaxIdentifierLength());
Expand Down Expand Up @@ -131,16 +132,67 @@ public static class RelationalIndexExtensions
return rootIndex.GetDatabaseName(storeObject);
}

var nameSegments = GetJsonPathNames(index) ?? columnNames;
var baseName = new StringBuilder()
.Append("IX_")
.Append(storeObject.Name)
.Append('_')
.AppendJoin(columnNames, "_")
.AppendJoin(nameSegments, "_")
.ToString();

return Uniquifier.Truncate(baseName, index.DeclaringEntityType.Model.GetMaxIdentifierLength());
}

private static IReadOnlyList<string>? GetJsonPathNames(IReadOnlyIndex index)
{
// For an index on properties contained inside a JSON-mapped complex type, the index covers
// a single JSON container column, so naming purely by column would produce ambiguous default
// names when multiple JSON-path indexes share a column. Use the property path through the
// complex-type chain (e.g. "Items_Value") instead so each path gets a distinct default name.
var segments = new List<string>();
foreach (var property in index.Properties)
{
switch (property)
{
case IReadOnlyProperty scalar
when scalar.DeclaringType is IReadOnlyComplexType complexType && complexType.IsMappedToJson():
{
var stack = new Stack<string>();
stack.Push(scalar.Name);
IReadOnlyTypeBase current = scalar.DeclaringType;
while (current is IReadOnlyComplexType ct)
{
stack.Push(ct.ComplexProperty.Name);
current = ct.ComplexProperty.DeclaringType;
}

segments.AddRange(stack);
break;
}

case IReadOnlyComplexProperty { ComplexType: var ct } when ct.IsMappedToJson():
{
var stack = new Stack<string>();
stack.Push(((IReadOnlyComplexProperty)property).Name);
IReadOnlyTypeBase current = ((IReadOnlyComplexProperty)property).DeclaringType;
while (current is IReadOnlyComplexType parentCt)
{
stack.Push(parentCt.ComplexProperty.Name);
current = parentCt.ComplexProperty.DeclaringType;
}

segments.AddRange(stack);
break;
}

default:
return null;
}
}

return segments;
}

/// <summary>
/// Sets the name of the index in the database.
/// </summary>
Expand Down
Loading
Loading