简体   繁体   中英

EF FOREIGN KEY constraint may cause cycles or multiple cascade paths

I am developing a sample application where people can place bets on sports events and earn points. It has the following Entity Framework Code-First models:

public class Person
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

public class Race
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }
}

public class RaceBet
{
    [Key]
    public int Id { get; set; }

    [Required]
    public int RaceId { get; set; }

    [Required]
    public int PersonId { get; set; }

    [Required]
    public int CompetitorId { get; set; }

    public virtual Race Race { get; set; }
    public virtual Person Person { get; set; }
    public virtual Person Competitor { get; set; }
}

A Person can place a bet for a Race and he can bet on any other Person (Competitor).

The models will produce the following error:

Introducing FOREIGN KEY constraint 'FK_dbo.RaceBets_dbo.People_PersonId' on table 'RaceBets' 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.

I tried removing the OneToManyCascadeDeleteConvention , adding fluent configurations to prevent cascade delete for RaceBet and all other variations of the api, but everything fails.

modelBuilder
.Entity<RaceBet>()
.HasRequired(x => x.Person)
.WithMany()
.HasForeignKey(x => x.PersonId)
.WillCascadeOnDelete(false);

How can I resolve this? Is the concept behind my models wrong?

Thanks!

Thanks to Oleg for his comment:

I can't to reproduce exception with this code: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add(new System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConventi‌​on()); modelBuilder .Entity() .HasRequired(x => x.Person) .WithMany() .HasForeignKey(x => x.PersonId) .WillCascadeOnDelete(false); }

This fixed the model creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM