0
votes

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!

1
I can't to reproduce exception with this code: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add(new System.Data.Entity.ModelConfiguration.Conventions.OneToManyCascadeDeleteConvention()); modelBuilder .Entity<RaceBet>() .HasRequired(x => x.Person) .WithMany() .HasForeignKey(x => x.PersonId) .WillCascadeOnDelete(false); }Oleg
There is no Error on my Part when I tried to copy paste your Model. Are you sure you have the same one on your project?Aizen

1 Answers

0
votes

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.