Configure Delete Behaviour in .NET Using EF Core Fluent API

What happens to children entities when you delete the parent entity? For example, what happens to books published by an author when the author is deleted from the system? You can decide to delete the books, or keep them without an author.

public class Book
{
   public int Id { get; set; }
   public string Title { get; set; }
   // other properties as necessary
   public int AuthorId { get; set; }
   public Person Author { get; set; }
}
public class Person
{
   public int Id { get; set; }
   public string Name { get; set; }
   // Optionally add a navigation property to an authors books
   // public IList<Book> Books { get; } = [];
}

The above is an example of a required relationship by convention because the AuthorId is non-nullable. This means that when an author is deleted, all of the books they authored are also deleted.

To avoid deleting books when the author is deleted, make the AuthorId foreign-key property nullable like so

public int? AuthorId { get; set; }

And then configure the relationship in the OnModelCreating method

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);
   modelBuilder.Entity<Book>()
       .HasOne(u => u.Author)
       .WithMany()
       .HasForeignKey(u => u.AuthorId)
       .OnDelete(DeleteBehavior.SetNull);
}

This will set the foreign-key property of the dependent entities (i.e. the books) to null instead of deleting them. These entities are known as orphans.