1

Good morning I don't see why sql server (with EF core) does not allow me to create the following table:

CREATE TABLE [UserRoles] (
    [UserId] int NOT NULL,
    [RoleId] int NOT NULL,
    CONSTRAINT [PK_UserRoles] PRIMARY KEY ([UserId], [RoleId]),
    CONSTRAINT [FK_UserRoles_Roles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [Roles] ([Id]) ON DELETE CASCADE,
    CONSTRAINT [FK_UserRoles_Users_UserId] FOREIGN KEY ([UserId]) REFERENCES [Users] ([Id]) ON DELETE CASCADE
);

I have the following error message:

Introducing a FOREIGN KEY constraint 'FK_UserRoles_Users_UserId' on the 'UserRoles' table may cause cycles or multiple cascading accesses. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

I want to keep both foreign key constraints if possible.

Should I add annotations to properties of the model "UserRoleModel"?

public class UserRoleModel : IdentityUserRole<int>
    {
        [NotMapped]
        public virtual UserModel User { get; set; }

        [NotMapped]
        public virtual RoleModel Role { get; set; }
    } 

Thanks in advance.

I can remove delete on cascale action from the migration script but this is not an optimal solution because each time if I regenerate the migration script I have to redo it.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Works fine https://dbfiddle.uk/-wO9XwQr you must have another pair of foreign keys somewhere which is causing multiple paths. – Charlieface Aug 08 '23 at 11:19

0 Answers0