Entity Framework Code First – Defining Relationships/Keys

This is exception caused by SQL server when you have multiple paths of cascade deletes. If you delete your PaymentTerm it will trigger cascade delete on all three relations. This will blow up when creating either SalesOrder or Invoice. EF creates by default all one-to-many relations with ON DELETE CASCADE you can remap your specific relation to not use it by:

modelBuilder.Entity<...>()
            .HasRequired(...)
            .WithMany(...)
            .HasForeignKey(...)
            .WillCascadeOnDelete(false);

Or you can turn it off globaly by removing the convention:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();   

You can get around this error on a particular migration by editing the generated Up() method with a line something like this:

AddForeignKey("dbo.Payments", "EventID", "dbo.Events", "EventID", cascadeDelete: true)

and change that cascadeDelete: value to false on the offending relationship(s).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)