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

Attribute for configuring DeleteBehavior #27630

Merged
merged 34 commits into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
2929859
Add DeleteBehaviorAttribute
Vekz Mar 10, 2022
25bf1d8
Add DeleteBehaviorAttribute Convention that sets delete behavior on f…
Vekz Mar 10, 2022
a903461
Register DeleteBehaviorAttributeConvention in ConventionSet provider
Vekz Mar 10, 2022
88b2376
Add tests for DeleteBehaviorAttribute
Vekz Mar 11, 2022
9ac476a
Make DeleteBehaviorAttribute a property or field attribute
Vekz Mar 11, 2022
c410304
Make changes to detect added foreign key
Vekz Mar 11, 2022
3a1693d
Add new registration in ConventionSet provider
Vekz Mar 11, 2022
6a59b7a
Add more test cases for different edge cases
Vekz Mar 11, 2022
7dc5a6f
Add more edge cases to tests
Vekz Mar 11, 2022
46d054b
Add test case for implicit foreign key
Vekz Mar 11, 2022
c454830
Cleanup convention and registration in provider
Vekz Mar 11, 2022
ac25537
Move DeleteBehavior enum and add TypeForward
Vekz Mar 11, 2022
e2aed9a
Make DeleteBehaviorAttribute code and tests use DeleteBehavior enum
Vekz Mar 11, 2022
fb34679
Add EFCore.Abstractions assembly to fix tests after TypeForwarding De…
Vekz Mar 11, 2022
c0e9b70
Make DeleteBehaviorAttribute descriptions more meaningful
Vekz Mar 23, 2022
95cc27e
Change formatting in DeleteBehaviorAttributeConvention and fix incorr…
Vekz Mar 23, 2022
12d700e
Simplify test suite for DeleteBehaviorAttribute and do some minor for…
Vekz Mar 23, 2022
8168b9f
Make tests reflect setting the attribute on navigation property
Vekz Mar 23, 2022
7e6d766
Take attribute value from being set on dependent navigation property …
Vekz Mar 23, 2022
af2e118
Limit use of the attribute to only properties to accomodate only sett…
Vekz Mar 23, 2022
256cb54
Throw InvalidOperationException when DeleteBehaviorAttribute is set o…
Vekz Mar 24, 2022
599f191
Add tests for when Attribute is set on different property than naviga…
Vekz Mar 24, 2022
4c71154
Make sure attribute is set only from dependent side
Vekz Apr 20, 2022
195673a
Make xml comments docs more readable
Vekz Apr 20, 2022
a92c66a
Simplify the convention
Vekz Apr 20, 2022
5357529
Add navigation attribute convention tests and adjust code to work cor…
Vekz Apr 21, 2022
8d9d189
Implement 1:1 relations delete behavior setting and restriction to th…
Vekz May 15, 2022
3a1da1d
Add 1:1 relationship tests and implement suggestions from PR
Vekz May 17, 2022
28b09bb
Add stylistic changes suggested by PR and IDE
Vekz May 18, 2022
665fdd8
Fix CoreStrings.resx merge conflicts
Vekz May 18, 2022
02860a3
Fix CoreStrings.resx merge conflicts
Vekz May 18, 2022
0460b8a
Merge branch 'main' into 9621_DeleteBehaviorAttribute
Vekz May 18, 2022
6fc84c1
Run Custom Tool on CoreStrings.Designer.tt
Vekz May 18, 2022
4cb7491
Add virtual modifier to the DeleteBehaviorAttributeConvention's publi…
Vekz May 18, 2022
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 @@ -10,12 +10,12 @@ namespace Microsoft.EntityFrameworkCore;
/// <remarks>
/// <para>
/// Behaviors in the database are dependent on the database schema being created
/// appropriately. Using Entity Framework Migrations or <see cref="DatabaseFacade.EnsureCreated" />
/// will create the appropriate schema.
/// appropriately. Using Entity Framework Migrations or
/// <c>EnsureCreated()</c> will create the appropriate schema.
/// </para>
/// <para>
/// Note that the in-memory behavior for entities that are currently tracked by
/// the <see cref="DbContext" /> can be different from the behavior that happens in the database.
/// the context can be different from the behavior that happens in the database.
/// </para>
/// <para>
/// See <see href="https://aka.ms/efcore-docs-cascading">Cascade delete and deleting orphans in EF Core</see> for more information and
Expand All @@ -25,16 +25,17 @@ namespace Microsoft.EntityFrameworkCore;
public enum DeleteBehavior
{
/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in
/// For entities being tracked by the context, the values of foreign key properties in
/// dependent entities are set to null when the related principal is deleted.
/// This helps keep the graph of entities in a consistent state while they are being tracked, such that a
/// fully consistent graph can then be written to the database. If a property cannot be set to null because
/// it is not a nullable type, then an exception will be thrown when <see cref="DbContext.SaveChanges()" /> is called.
/// it is not a nullable type, then an exception will be thrown when
/// <c>SaveChanges()</c> is called.
/// </summary>
/// <remarks>
/// <para>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database
/// <c>EnsureCreated()</c> method, then the behavior in the database
/// is to generate an error if a foreign key constraint is violated.
/// </para>
/// <para>
Expand All @@ -45,29 +46,30 @@ public enum DeleteBehavior
ClientSetNull,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in
/// dependent entities are set to null when the related principal is deleted.
/// For entities being tracked by the context, the values of foreign key properties in dependent entities
/// are set to null when the related principal is deleted.
/// This helps keep the graph of entities in a consistent state while they are being tracked, such that a
/// fully consistent graph can then be written to the database. If a property cannot be set to null because
/// it is not a nullable type, then an exception will be thrown when <see cref="DbContext.SaveChanges()" /> is called.
/// it is not a nullable type, then an exception will be thrown when
/// <c>SaveChanges()</c> is called.
/// </summary>
/// <remarks>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database
/// is to generate an error if a foreign key constraint is violated.
/// <c>EnsureCreated()</c> method, then the behavior in the database is to generate an error if a foreign key constraint is violated.
/// </remarks>
Restrict,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in
/// For entities being tracked by the context, the values of foreign key properties in
/// dependent entities are set to null when the related principal is deleted.
/// This helps keep the graph of entities in a consistent state while they are being tracked, such that a
/// fully consistent graph can then be written to the database. If a property cannot be set to null because
/// it is not a nullable type, then an exception will be thrown when <see cref="DbContext.SaveChanges()" /> is called.
/// it is not a nullable type, then an exception will be thrown when
/// <c>SaveChanges()</c> is called.
/// </summary>
/// <remarks>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database is
/// <c>EnsureCreated()</c> method, then the behavior in the database is
/// the same as is described above for tracked entities. Keep in mind that some databases cannot easily
/// support this behavior, especially if there are cycles in relationships, in which case it may
/// be better to use <see cref="ClientSetNull" /> which will allow EF to cascade null values
Expand All @@ -76,13 +78,13 @@ public enum DeleteBehavior
SetNull,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, dependent entities
/// For entities being tracked by the context, dependent entities
/// will be deleted when the related principal is deleted.
/// </summary>
/// <remarks>
/// <para>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database is
/// <c>EnsureCreated()</c> method, then the behavior in the database is
/// the same as is described above for tracked entities. Keep in mind that some databases cannot easily
/// support this behavior, especially if there are cycles in relationships, in which case it may
/// be better to use <see cref="ClientCascade" /> which will allow EF to perform cascade deletes
Expand All @@ -96,27 +98,25 @@ public enum DeleteBehavior
Cascade,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, dependent entities
/// For entities being tracked by the context, dependent entities
/// will be deleted when the related principal is deleted.
/// </summary>
/// <remarks>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database
/// is to generate an error if a foreign key constraint is violated.
/// <c>EnsureCreated()</c> method, then the behavior in the database is to generate an error if a foreign key constraint is violated.
/// </remarks>
ClientCascade,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in
/// dependent entities are set to null when the related principal is deleted.
/// For entities being tracked by the context, the values of foreign key properties in dependent entities are set to null when the related principal is deleted.
/// This helps keep the graph of entities in a consistent state while they are being tracked, such that a
/// fully consistent graph can then be written to the database. If a property cannot be set to null because
/// it is not a nullable type, then an exception will be thrown when <see cref="DbContext.SaveChanges()" /> is called.
/// it is not a nullable type, then an exception will be thrown when
/// <c>SaveChanges()</c> is called.
/// </summary>
/// <remarks>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database
/// is to generate an error if a foreign key constraint is violated.
/// <c>EnsureCreated()</c> method, then the behavior in the database is to generate an error if a foreign key constraint is violated.
/// </remarks>
NoAction,

Expand All @@ -126,15 +126,13 @@ public enum DeleteBehavior
/// </summary>
/// <remarks>
/// <para>
/// For entities being tracked by the <see cref="DbContext" />, the values of foreign key properties in
/// dependent entities are not changed when the related principal entity is deleted.
/// For entities being tracked by the context, the values of foreign key properties in dependent entities are not changed when the related principal entity is deleted.
/// This can result in an inconsistent graph of entities where the values of foreign key properties do
/// not match the relationships in the graph.
/// </para>
/// <para>
/// If the database has been created from the model using Entity Framework Migrations or the
/// <see cref="DatabaseFacade.EnsureCreated" /> method, then the behavior in the database
/// is to generate an error if a foreign key constraint is violated.
/// <c>EnsureCreated()</c> method, then the behavior in the database is to generate an error if a foreign key constraint is violated.
/// </para>
/// </remarks>
ClientNoAction
Expand Down
29 changes: 29 additions & 0 deletions src/EFCore.Abstractions/DeleteBehaviorAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.EntityFrameworkCore;

/// <summary>
/// Configures the property or field to indicate how a delete operation is applied to dependent entities
Copy link
Member

@AndriySvyryd AndriySvyryd May 17, 2022

Choose a reason for hiding this comment

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

Suggested change
/// Configures the property or field to indicate how a delete operation is applied to dependent entities
/// Configures the navigation property on the dependent side of a relationship to indicate how a delete operation is applied to dependent entities

/// in a relationship when it is deleted or the relationship is severed.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public sealed class DeleteBehaviorAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBehaviorAttribute" /> class.
/// </summary>
/// <param name="behavior">The <see cref="DeleteBehavior" /> to be configured.</param>
public DeleteBehaviorAttribute(DeleteBehavior behavior)
{
Behavior = behavior;
}

/// <summary>
/// The <see cref="DeleteBehavior" /> to be configured.
/// </summary>
public DeleteBehavior Behavior { get; }
}
128 changes: 128 additions & 0 deletions src/EFCore/Metadata/Conventions/DeleteBehaviorAttributeConvention.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace Microsoft.EntityFrameworkCore.Metadata.Conventions;

/// <summary>
/// A convention that configures the delete behavior based on the <see cref="DeleteBehaviorAttribute" /> applied on the property.
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-conventions">Model building conventions</see> for more information and examples.
/// </remarks>
public class DeleteBehaviorAttributeConvention : PropertyAttributeConventionBase<DeleteBehaviorAttribute>, INavigationAddedConvention, IForeignKeyPrincipalEndChangedConvention, IModelFinalizingConvention
{
/// <summary>
/// Creates a new instance of <see cref="DeleteBehaviorAttributeConvention" />.
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this convention.</param>
public DeleteBehaviorAttributeConvention(ProviderConventionSetBuilderDependencies dependencies)
: base(dependencies) { }

/// <summary>
/// Called after a property is added to the entity type with an attribute on the associated CLR property or field.
/// </summary>
/// <param name="propertyBuilder">The builder for the property.</param>
/// <param name="attribute">The attribute.</param>
/// <param name="clrMember">The member that has the attribute.</param>
/// <param name="context">Additional information associated with convention execution.</param>
protected override void ProcessPropertyAdded(
IConventionPropertyBuilder propertyBuilder,
DeleteBehaviorAttribute attribute,
MemberInfo clrMember,
IConventionContext context)
{
throw new InvalidOperationException(CoreStrings.DeleteBehaviorAttributeNotOnNavigationProperty);
}

/// <summary>
/// Called after a navigation is added to the entity type.
/// </summary>
/// <param name="navigationBuilder">The builder for the navigation.</param>
/// <param name="context">Additional information associated with convention execution.</param>
public void ProcessNavigationAdded(IConventionNavigationBuilder navigationBuilder, IConventionContext<IConventionNavigationBuilder> context)
{
var navAttribute = navigationBuilder.Metadata.PropertyInfo?.GetCustomAttribute<DeleteBehaviorAttribute>();
if (navAttribute == null)
{
return;
}

if (!navigationBuilder.Metadata.IsOnDependent)
{
throw new InvalidOperationException(CoreStrings.DeleteBehaviorAttributeOnPrincipalProperty);
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
}

var foreignKey = navigationBuilder.Metadata.ForeignKey;
if (foreignKey.IsUnique)
{
return;
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
}

if (foreignKey.GetDeleteBehaviorConfigurationSource() != ConfigurationSource.Explicit)
{
foreignKey.SetDeleteBehavior(navAttribute.Behavior);
}
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
/// Called after the principal end of a foreign key is changed.
/// </summary>
/// <param name="relationshipBuilder">The builder for the foreign key.</param>
/// <param name="context">Additional information associated with convention execution.</param>
public void ProcessForeignKeyPrincipalEndChanged(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext<IConventionForeignKeyBuilder> context)
{
if (!relationshipBuilder.Metadata.IsUnique)
{
return;
}

var navigation = relationshipBuilder.Metadata.DependentToPrincipal;
if (navigation == null)
{
return;
}

var navAttribute = navigation.PropertyInfo?.GetCustomAttribute<DeleteBehaviorAttribute>();
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
if (navAttribute == null)
{
return;
}

if (relationshipBuilder.Metadata.GetDeleteBehaviorConfigurationSource() != ConfigurationSource.Explicit)
{
relationshipBuilder.Metadata.SetDeleteBehavior(navAttribute.Behavior);
}
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
/// Called when a model is being finalized.
/// </summary>
/// <param name="modelBuilder">The builder for the model.</param>
/// <param name="context">Additional information associated with convention execution.</param>
public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext<IConventionModelBuilder> context)
{
foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
{
foreach (var navigation in entityType.GetNavigations())
{
if (!navigation.ForeignKey.IsUnique)
{
return;
}

var navAttribute = navigation.PropertyInfo?.GetCustomAttribute<DeleteBehaviorAttribute>();
if (navAttribute == null)
{
return;
}

if (!navigation.IsOnDependent)
{
throw new InvalidOperationException(CoreStrings.DeleteBehaviorAttributeOnPrincipalProperty);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ public virtual ConventionSet CreateConventionSet()
var backingFieldAttributeConvention = new BackingFieldAttributeConvention(Dependencies);
var unicodeAttributeConvention = new UnicodeAttributeConvention(Dependencies);
var precisionAttributeConvention = new PrecisionAttributeConvention(Dependencies);
var deleteBehaviorAttributeConvention = new DeleteBehaviorAttributeConvention(Dependencies);

conventionSet.PropertyAddedConventions.Add(backingFieldAttributeConvention);
conventionSet.PropertyAddedConventions.Add(backingFieldConvention);
Expand All @@ -129,6 +130,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.PropertyAddedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.PropertyAddedConventions.Add(unicodeAttributeConvention);
conventionSet.PropertyAddedConventions.Add(precisionAttributeConvention);
conventionSet.PropertyAddedConventions.Add(deleteBehaviorAttributeConvention);

conventionSet.EntityTypePrimaryKeyChangedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.EntityTypePrimaryKeyChangedConventions.Add(valueGeneratorConvention);
Expand Down Expand Up @@ -184,6 +186,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.NavigationAddedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.NavigationAddedConventions.Add(relationshipDiscoveryConvention);
conventionSet.NavigationAddedConventions.Add(foreignKeyAttributeConvention);
conventionSet.NavigationAddedConventions.Add(deleteBehaviorAttributeConvention);

var manyToManyJoinEntityTypeConvention = new ManyToManyJoinEntityTypeConvention(Dependencies);
conventionSet.SkipNavigationAddedConventions.Add(new NavigationBackingFieldAttributeConvention(Dependencies));
Expand Down Expand Up @@ -211,6 +214,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.ForeignKeyPrincipalEndChangedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.ForeignKeyPrincipalEndChangedConventions.Add(requiredNavigationAttributeConvention);
conventionSet.ForeignKeyPrincipalEndChangedConventions.Add(nonNullableNavigationConvention);
conventionSet.ForeignKeyPrincipalEndChangedConventions.Add(deleteBehaviorAttributeConvention);

conventionSet.PropertyNullabilityChangedConventions.Add(foreignKeyPropertyDiscoveryConvention);

Expand Down Expand Up @@ -239,6 +243,7 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.ModelFinalizingConventions.Add(new QueryFilterRewritingConvention(Dependencies));
conventionSet.ModelFinalizingConventions.Add(inversePropertyAttributeConvention);
conventionSet.ModelFinalizingConventions.Add(backingFieldConvention);
conventionSet.ModelFinalizingConventions.Add(deleteBehaviorAttributeConvention);

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

Expand Down
Loading