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

Configure OnDelete for join entity types on SQL Server #21959

Merged
2 commits merged into from
Aug 6, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ public override ConventionSet CreateConventionSet()

ReplaceConvention(conventionSet.ForeignKeyRemovedConventions, valueGenerationConvention);

conventionSet.SkipNavigationForeignKeyChangedConventions.Add(new SqlServerOnDeleteConvention(Dependencies, RelationalDependencies));

conventionSet.IndexAddedConventions.Add(sqlServerInMemoryTablesConvention);
conventionSet.IndexAddedConventions.Add(sqlServerIndexConvention);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;

// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
{
/// <summary>
/// A convention that configures the OnDelete behavior for foreign keys on the join entity type for
/// self-referencing skip navigations
/// </summary>
public class SqlServerOnDeleteConvention : ISkipNavigationForeignKeyChangedConvention
{
/// <summary>
/// Creates a new instance of <see cref="SqlServerOnDeleteConvention" />.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this convention. </param>
/// <param name="relationalDependencies"> Parameter object containing relational dependencies for this convention. </param>
public SqlServerOnDeleteConvention(
[NotNull] ProviderConventionSetBuilderDependencies dependencies,
[NotNull] RelationalConventionSetBuilderDependencies relationalDependencies)
{
}

/// <inheritdoc />
public void ProcessSkipNavigationForeignKeyChanged(
IConventionSkipNavigationBuilder skipNavigationBuilder,
IConventionForeignKey foreignKey,
IConventionForeignKey oldForeignKey,
IConventionContext<IConventionForeignKey> context)
{
var selfReferencingSkipNavigation = skipNavigationBuilder.Metadata;
if (foreignKey == null
|| selfReferencingSkipNavigation.Inverse == null
|| selfReferencingSkipNavigation.TargetEntityType != selfReferencingSkipNavigation.DeclaringEntityType)
{
return;
}

if (selfReferencingSkipNavigation == selfReferencingSkipNavigation.DeclaringEntityType.GetDeclaredSkipNavigations()
.First(s => s == selfReferencingSkipNavigation || s == selfReferencingSkipNavigation.Inverse))
{
foreignKey.Builder.OnDelete(DeleteBehavior.ClientCascade);
selfReferencingSkipNavigation.Inverse.ForeignKey?.Builder.OnDelete(null);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,8 @@ public SqlServerValueGenerationStrategyConvention(
[NotNull] ProviderConventionSetBuilderDependencies dependencies,
[NotNull] RelationalConventionSetBuilderDependencies relationalDependencies)
{
Dependencies = dependencies;
}

/// <summary>
/// Parameter object containing service dependencies.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }

/// <summary>
/// Called after a model is initialized.
/// </summary>
Expand Down
4 changes: 2 additions & 2 deletions src/EFCore/Metadata/Conventions/IForeignKeyAddedConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ public interface IForeignKeyAddedConvention : IConvention
/// <summary>
/// Called after a foreign key is added to the entity type.
/// </summary>
/// <param name="relationshipBuilder"> The builder for the foreign key. </param>
/// <param name="foreignKeyBuilder"> The builder for the foreign key. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
void ProcessForeignKeyAdded(
[NotNull] IConventionForeignKeyBuilder relationshipBuilder,
[NotNull] IConventionForeignKeyBuilder foreignKeyBuilder,
[NotNull] IConventionContext<IConventionForeignKeyBuilder> context);
}
}
2 changes: 1 addition & 1 deletion src/EFCore/Metadata/Conventions/KeyDiscoveryConvention.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ protected virtual void TryConfigurePrimaryKey([NotNull] IConventionEntityTypeBui
{
var manyToManyForeignKeys = entityType.GetForeignKeys()
.Where(fk => fk.GetReferencingSkipNavigations().Any(n => n.IsCollection)).ToList();
if (manyToManyForeignKeys.Count() == 2)
if (manyToManyForeignKeys.Count == 2)
{
keyProperties.AddRange(manyToManyForeignKeys.SelectMany(fk => fk.Properties));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
Expand Down Expand Up @@ -109,7 +110,12 @@ private void CreateJoinEntityType(IConventionSkipNavigationBuilder skipNavigatio
var inverseEntityType = inverseSkipNavigation.DeclaringEntityType;
var model = declaringEntityType.Model;

var joinEntityTypeName = declaringEntityType.ShortName() + inverseEntityType.ShortName();
var joinEntityTypeName = declaringEntityType.ShortName();
var inverseName = inverseEntityType.ShortName();
joinEntityTypeName = StringComparer.Ordinal.Compare(joinEntityTypeName, inverseName) < 0
? joinEntityTypeName + inverseName
: inverseName + joinEntityTypeName;

if (model.FindEntityType(joinEntityTypeName) != null)
{
var otherIdentifiers = model.GetEntityTypes().ToDictionary(et => et.Name, et => 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con
.WithMany(e => e.SelfSkipPayloadRight)
.UsingEntity<JoinOneSelfPayload>(
l => l.HasOne(x => x.Left).WithMany(x => x.JoinSelfPayloadLeft),
r => r.HasOne(x => x.Right).WithMany(x => x.JoinSelfPayloadRight).OnDelete(DeleteBehavior.ClientCascade));
r => r.HasOne(x => x.Right).WithMany(x => x.JoinSelfPayloadRight));

// Nav:2 Payload:No Join:Concrete Extra:Inheritance
modelBuilder.Entity<EntityOne>()
Expand Down Expand Up @@ -232,7 +232,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext con
.UsingEntity<Dictionary<string, object>>(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this pair be configured by convention? (I can update that as it can cause SQL assertion updates)

Copy link
Member Author

@AndriySvyryd AndriySvyryd Aug 6, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I changed the convention for the FK properties and added TODOs here so you can remove the usings.

"JoinTwoSelfShared",
l => l.HasOne<EntityTwo>().WithMany().HasForeignKey("LeftId"),
r => r.HasOne<EntityTwo>().WithMany().HasForeignKey("RightId").OnDelete(DeleteBehavior.NoAction));
r => r.HasOne<EntityTwo>().WithMany().HasForeignKey("RightId"));

// Nav:2 Payload:No Join:Shared Extra:CompositeKey
modelBuilder.Entity<EntityTwo>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
namespace Microsoft.EntityFrameworkCore
{
public abstract class ManyToManyTrackingSqlServerTestBase<TFixture> : ManyToManyTrackingTestBase<TFixture>
where TFixture : ManyToManyTrackingTestBase<TFixture>.ManyToManyTrackingFixtureBase
where TFixture : ManyToManyTrackingSqlServerTestBase<TFixture>.ManyToManyTrackingSqlServerFixtureBase
{
protected ManyToManyTrackingSqlServerTestBase(TFixture fixture)
: base(fixture)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ public void Join_entity_type_is_created_for_self_join()

RunConvention(firstSkipNav);

Assert.Single(manyToManySelf.Metadata.Model.GetEntityTypes()
.Where(et => et.IsImplicitlyCreatedJoinEntityType));
var joinEntityType = manyToManySelf.Metadata.Model.GetEntityTypes()
.Single(et => et.IsImplicitlyCreatedJoinEntityType);
Assert.Equal("ManyToManySelfManyToManySelf", joinEntityType.Name);
}

[ConditionalFact]
Expand Down Expand Up @@ -222,7 +223,7 @@ public void Join_entity_type_is_created()
ConfigurationSource.Convention);
skipNavOnFirst.HasInverse(skipNavOnSecond.Metadata, ConfigurationSource.Convention);

RunConvention(skipNavOnFirst);
RunConvention(skipNavOnSecond);

var joinEntityType = manyToManyFirst.Metadata.Model.GetEntityTypes()
.Single(et => et.IsImplicitlyCreatedJoinEntityType);
Expand Down