I want to create 2 tables: Team, Match, where in the Match table there are 2 references to the Team table. When I try to generate a database, I get an error related to cascade deletion. Can you tell me how to solve the problem?

public class Team { public int Id { get; set; } public string Name { get; set; } } public class Match { public int Id { get; set; } public int? HomeId { get; set; } public int? GuestId { get; set; } public Team Home { get; set; } public Team Guest { get; set; } } 
  • Disable via .OnDelete(DeleteBehavior.Restrict) in modelBinder. Theory here: metanit.com/sharp/entityframeworkcore/3.2.php - AK
  • And I do not really understand the subject area, but it seems to me that both home and guest teams are known for any match - so I would replace int? on int. - AK
  • @AK thanks a lot, I'll check now - Alex Kleshevnikov
  • Wow, completely out of my head: once I had already written myself a memo on this issue. - AK

1 answer 1

First, you need to set the navigation properties to the end:

 public class Team { public int Id { get; set; } public string Name { get; set; } public virtual IEnumerable<Match> HomeMatches { get; set; } public virtual IEnumerable<Match> GuestMatches { get; set; } } public class Match { public int Id { get; set; } public int HomeId { get; set; } public int GuestId { get; set; } public Team Home { get; set; } public Team Guest { get; set; } } 

Secondly, in ApplicationDbContext add:

 protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<Match>() .HasOne(m => m.Home) .WithMany(t => t.HomeMatches) .OnDelete(DeleteBehavior.Restrict); builder.Entity<Match>() .HasOne(m => m.Guest) .WithMany(t => t.GuestMatches) .OnDelete(DeleteBehavior.Restrict); } 

(Formally, one cascade would be enough to disconnect)

There are details on the metaint: https://metanit.com/sharp/entityframeworkcore/3.2.php

  • It is not necessary to arrange navigation properties to the end :-) - Pavel Mayorov
  • @PavelMayorov Do not teach children the bad;) - AK
  • Sometimes bad is just extra cycles in the object graph ... - Pavel Mayorov
  • @PavelMayorov Curious. An example of a link or where to read? - AK