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 14 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,15 @@ 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" />
/// appropriately. Using Entity Framework Migrations or
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
/// EnsureCreated()</see>
/// 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 <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">DbContext</see>
/// 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 +28,20 @@ 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 <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.savechanges?view=efcore-6.0#microsoft-entityframeworkcore-dbcontext-savechanges" >
/// SaveChanges()</see> 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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 +52,35 @@ 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 <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.savechanges?view=efcore-6.0#microsoft-entityframeworkcore-dbcontext-savechanges" >
/// SaveChanges()</see> 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.
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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 <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.savechanges?view=efcore-6.0#microsoft-entityframeworkcore-dbcontext-savechanges" >
/// SaveChanges()</see> 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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 +89,15 @@ public enum DeleteBehavior
SetNull,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, dependent entities
/// For entities being tracked by the <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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 +111,30 @@ public enum DeleteBehavior
Cascade,

/// <summary>
/// For entities being tracked by the <see cref="DbContext" />, dependent entities
/// For entities being tracked by the <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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.
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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 <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.savechanges?view=efcore-6.0#microsoft-entityframeworkcore-dbcontext-savechanges" >
/// SaveChanges()</see> 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.
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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 +144,15 @@ 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 <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext">
/// DbContext</see>, 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.
/// <see href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensurecreated">
/// EnsureCreated()</see> 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
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
/// 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 | AttributeTargets.Field)]
public sealed class DeleteBehaviorAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBehaviorAttribute" /> class.
/// </summary>
/// <param name="behavior">The DeleteBehavior value of entity</param>
public DeleteBehaviorAttribute(DeleteBehavior behavior)
{
Behavior = behavior;
}

/// <summary>
/// The DeleteBehavior value
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
public DeleteBehavior Behavior { get; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// 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.Metadata.Conventions;

/// <summary>
/// A convention that configures the DeleteBehavior based on the <see cref="DeleteBehaviorAttribute" /> applied on the property.
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-conventions">Model building conventions</see> for more information and examples.
/// </remarks>
public class DeleteBehaviorAttributeConvention : IForeignKeyAddedConvention
{
/// <summary>
/// Creates a new instance of <see cref="UnicodeAttributeConvention" />.
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this convention.</param>
public DeleteBehaviorAttributeConvention(ProviderConventionSetBuilderDependencies dependencies)
{
Dependencies = dependencies;
}

/// <summary>
/// Dependencies for this service.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }

/// <summary>
/// Called after a foreign key is added to the entity type.
/// </summary>
/// <param name="foreignKeyBuilder">The builder for the foreign key.</param>
/// <param name="context">Additional information associated with convention execution.</param>
public virtual void ProcessForeignKeyAdded(IConventionForeignKeyBuilder foreignKeyBuilder, IConventionContext<IConventionForeignKeyBuilder> context)
{
var foreignKey = foreignKeyBuilder.Metadata;
var properties = foreignKey.Properties;
foreach (var property in properties)
{
var attribute = property?.PropertyInfo?.GetCustomAttribute<DeleteBehaviorAttribute>();
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
AndriySvyryd marked this conversation as resolved.
Show resolved Hide resolved
if (attribute != null)
{
foreignKey.SetDeleteBehavior(attribute.Behavior);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -141,13 +141,15 @@ public virtual ConventionSet CreateConventionSet()
conventionSet.KeyRemovedConventions.Add(keyDiscoveryConvention);

var cascadeDeleteConvention = new CascadeDeleteConvention(Dependencies);
var deleteBehaviorAttributeConvention = new DeleteBehaviorAttributeConvention(Dependencies);

conventionSet.ForeignKeyAddedConventions.Add(foreignKeyAttributeConvention);
conventionSet.ForeignKeyAddedConventions.Add(foreignKeyPropertyDiscoveryConvention);
conventionSet.ForeignKeyAddedConventions.Add(keyDiscoveryConvention);
conventionSet.ForeignKeyAddedConventions.Add(valueGeneratorConvention);
conventionSet.ForeignKeyAddedConventions.Add(cascadeDeleteConvention);
conventionSet.ForeignKeyAddedConventions.Add(foreignKeyIndexConvention);
conventionSet.ForeignKeyAddedConventions.Add(deleteBehaviorAttributeConvention);

conventionSet.ForeignKeyRemovedConventions.Add(baseTypeDiscoveryConvention);
conventionSet.ForeignKeyRemovedConventions.Add(relationshipDiscoveryConvention);
Expand Down
1 change: 1 addition & 0 deletions src/EFCore/Properties/TypeForwards.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
[assembly: TypeForwardedTo(typeof(ObservableCollectionExtensions))]
[assembly: TypeForwardedTo(typeof(ObservableCollectionListSource<>))]
[assembly: TypeForwardedTo(typeof(SortableBindingList<>))]
[assembly: TypeForwardedTo(typeof(DeleteBehavior))]
Original file line number Diff line number Diff line change
Expand Up @@ -6083,6 +6083,7 @@ protected virtual ICollection<BuildReference> GetReferences()
=> new List<BuildReference>
{
BuildReference.ByName("Microsoft.EntityFrameworkCore"),
BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions"),
BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer"),
BuildReference.ByName("NetTopologySuite")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2023,6 +2023,7 @@ protected IModel BuildModelFromSnapshotSource(string code)

// Add standard EF references, a reference to the provider's assembly, and any extra references added by the provider's test suite
build.References.Add(BuildReference.ByName("Microsoft.EntityFrameworkCore"));
build.References.Add(BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions"));
build.References.Add(BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"));

var databaseProvider = Fixture.TestHelpers.CreateContextServices().GetRequiredService<IDatabaseProvider>();
Expand Down
Loading