Entity Framework Core: How to solve Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

In your sample code in OnModelCreating you have declared modelBuilder.Entity<AnEventUser>().HasOne(e => e.User)... twice: at start of method and at end.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AnEventUser>()       // THIS IS FIRST
        .HasOne(u => u.User).WithMany(u => u.AnEventUsers).IsRequired().OnDelete(DeleteBehavior.Restrict);


    modelBuilder.Entity<AnEventUser>()
        .HasKey(t => new { t.AnEventId, t.UserId });

    modelBuilder.Entity<AnEventUser>()
        .HasOne(pt => pt.AnEvent)
        .WithMany(p => p.AnEventUsers)
        .HasForeignKey(pt => pt.AnEventId);

    modelBuilder.Entity<AnEventUser>()       // THIS IS SECOND.
        .HasOne(eu => eu.User)               // THIS LINES
        .WithMany(e => e.AnEventUsers)       //   SHOULD BE
        .HasForeignKey(eu => eu.UserId);     //   REMOVED

}

Second call overrides first. Remove it.


This is what I did from the answer of Dmitry,

and It worked for me.

Class:

public class EnviornmentControls
{
    public int Id { get; set; }
    ...

    public virtual Environment Environment { get; set; }
}

And it's Mapping

public EnviornmentControlsMap(EntityTypeBuilder<EnviornmentControls> entity)
{
        entity.HasKey(m => m.Id);           

        entity.HasOne(m => m.Environment)
            .WithMany(m => m.EnviornmentControls)
            .HasForeignKey(m => m.EnvironmentID)
            .OnDelete(DeleteBehavior.Restrict); // added OnDelete to avoid sercular reference 
}