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

后端 未结 4 952
清酒与你
清酒与你 2021-01-11 10:30

I\'m using Entity Framework Core with Code First approach but recieve following error when updating the database:

Introducing FOREIGN KEY constraint \

4条回答
  •  青春惊慌失措
    2021-01-11 11:06

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity()       // THIS IS FIRST
            .HasOne(u => u.User).WithMany(u => u.AnEventUsers).IsRequired().OnDelete(DeleteBehavior.Restrict);
    
    
        modelBuilder.Entity()
            .HasKey(t => new { t.AnEventId, t.UserId });
    
        modelBuilder.Entity()
            .HasOne(pt => pt.AnEvent)
            .WithMany(p => p.AnEventUsers)
            .HasForeignKey(pt => pt.AnEventId);
    
        modelBuilder.Entity()       // 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.

提交回复
热议问题