17

I have a configuration like this in my codes:

builder.HasMany(c => c.Libs)
       .WithOne(x=>x.Book)
       .HasForeignKey(x=>x.BookId)
       .OnDelete(DeleteBehavior.NoAction);  <<-------- Here

My question is what is different between NoAction and Restrict value?

I read Microsoft document and descriptions of both of them are same!!!

enter image description here

Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98

2 Answers2

7

It depends on the database implementation.

In T-SQL and MySQL, there is no difference.

In PostgreSQL, there is a difference: Difference between RESTRICT and NO ACTION

arni
  • 2,152
  • 19
  • 14
-2

The delete behavior defines the action that will be taken when the parent entity in a PK-FK relationship is deleted. In this case, the parent entity is Book and the Child entity is Libs, with 1:many relationship.

NoAction: In this case, when a row from Book table is deleted from the database, all the rows from Libs table that have BookId same as deleted BookId, will be converted to null. Note that this method does not delete any items from Libs table, and can leave them orphaned.

Restrict: In this case, when a row from Book table can only be deleted from the database if there are no associated Libs with the same BookId. Note that you can only delete the Book row once you have deleted all the associated Libs.

Cascade: In this case, all the associated Libs rows from the books will be automatically deleted if the Book row is deleted.

Ayush Jain
  • 75
  • 2
  • 2
    What is your reference? – Ramin Bateni Oct 12 '20 at 15:02
  • 1
    The source is one of the links that you provided: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.deletebehavior?view=efcore-3.1 Also, we use the 3 mentioned behaviors in our projects. – Ayush Jain Oct 13 '20 at 01:10
  • 2
    The documentation describes IDENTICAL behavior for NoAction and Restrict. In both cases, "the values of foreign key properties in dependent entities are set to null when the related principal is deleted". In both cases, if you delete the related entity with both entities loaded in memory, the null value is saved to the database. And in both cases, if the related entity is deleted without the dependent entity being loaded in memory, the dependent entity's db row is not updated, and an exception will occur when the foreign key constraint is validated. Both options behave identically. – Benjamin Ray Oct 26 '20 at 16:54