EF6 Code First - may cause loops or multiple cascading paths

I am using EF6 Code First. I have two classes:

public class Player { [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] [Key] public int Id { get; set; } [Required, MinLength(2, ErrorMessage = "Player name must be at least 2 characters length")] public string Name { get; set; } [Required] public int TeamClubId { get; set; } [Required] public int TeamNationalId { get; set; } [Required, ForeignKey("TeamClubId")] public virtual Team Club { get; set; } [Required, ForeignKey("TeamNationalId")] public virtual Team National { get; set; } } 

AND:

  public class Team { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")] public string Name { get; set; } [Required] public TeamType Type { get; set; } public virtual ICollection<Player> Players { get; set; } } 

These are my two classes with their relationship. The player belongs to two teams: club and national teams. A team can be either club or national, and contains a collection of players.

In my context file, I use:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Player>() .HasRequired<Team>(p => p.National) .WithMany(t => t.Players) .WillCascadeOnDelete(false); base.OnModelCreating(modelBuilder); } 

When I run the migration tool to update the database, I get the following error:

Representation of the FOREIGN KEY constraint "FK_dbo.Players_dbo.Teams_TeamNationalId" in the Players table may cause loops or multiple cascading paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION or change other FOREIGN KEY constraints. Failed to create constraint. See Previous Errors.

How to solve it?

+7
source share
2 answers

Using the Fluent API:

  //player - national team relations modelBuilder.Entity<Player>() .HasRequired<Team>(p => p.National) .WithMany() .WillCascadeOnDelete(false); //player - club team relations modelBuilder.Entity<Player>() .HasRequired<Team>(p => p.Club) .WithMany() .WillCascadeOnDelete(false); 
+9
source

I think your Team has only one navigation property for two different foreign keys pointing to it, may be a problem with your EF code. It is probably more acceptable to have two navigation properties on your Team - one for each foreign key pointing to it.

0
source

All Articles