EF6 Code First - may cause cycles or multiple cascade paths

别来无恙 提交于 2019-11-29 19:42:06

问题


I'm 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 class with their relationship. A player belongs to two teams: club and national teams. A team can be either club or national, and holds a collection of player.

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 running the migration tool to update the database, I get the following error:

Introducing FOREIGN KEY constraint 'FK_dbo.Players_dbo.Teams_TeamNationalId' on table 'Players' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

How do I solve it?


回答1:


Using 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);



回答2:


I think the fact that your Team only has a single navigation property for two different foreign keys pointing to it might be a problem with your EF code. It's probably more acceptable to have two navigation properties on your Team - one for each foreign key pointing to it.



来源:https://stackoverflow.com/questions/21390621/ef6-code-first-may-cause-cycles-or-multiple-cascade-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!