I feel that there is a ton of ambiguity in Stack Overflow on questions regarding disabling the cascading deletion feature by EF Core 6 for many-many relationships. I've spent hours wrestling with this question and cannot find an answer on the Microsoft docs or on Stack Overflow. How can I change my code to disable cascade deletion on my many-many relationship below?
SuggestionModel.cs
[Key]
public long SuggestionId { get; set; }
...
public ICollection<UserModel> UserVotes { get; set; } = new HashSet<UserModel>();
...
UserModel.cs
[Key]
public long UserId { get; set; }
...
public ICollection<SuggestionModel> VotedOnSuggestions { get; set; } = new List<SuggestionModel>();
...
DbConnection.cs (DbContext class)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
modelBuilder.Entity<UserModel>().HasData(user1, user2, user3, user4);
modelBuilder.Entity<SuggestionModel>().HasData(suggestion1, suggestion2, suggestion3, suggestion4, suggestion5);
modelBuilder.Entity<SuggestionModel>().HasMany(s => s.UserVotes).WithMany(u => u.VotedOnSuggestions)
.UsingEntity(e => e.HasData(
new { VotedOnSuggestionsSuggestionId = 4L, UserVotesUserId = 1L },
new { VotedOnSuggestionsSuggestionId = 4L, UserVotesUserId = 2L },
new { VotedOnSuggestionsSuggestionId = 4L, UserVotesUserId = 3L },
new { VotedOnSuggestionsSuggestionId = 5L, UserVotesUserId = 1L },
new { VotedOnSuggestionsSuggestionId = 5L, UserVotesUserId = 2L },
new { VotedOnSuggestionsSuggestionId = 5L, UserVotesUserId = 3L },
new { VotedOnSuggestionsSuggestionId = 5L, UserVotesUserId = 4L }
));
}
The exact error
Microsoft.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN KEY constraint
'FK_SuggestionModelUserModel_Users_UserVotesUserId' on table 'SuggestionModelUserModel'
may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO
ACTION, or modify other FOREIGN KEY constraints.
SQL Command that caused the error
Failed executing DbCommand (10ms) [Parameters=[], CommandType='Text',
CommandTimeout='30']
CREATE TABLE [SuggestionModelUserModel] (
[UserVotesUserId] bigint NOT NULL,
[VotedOnSuggestionsSuggestionId] bigint NOT NULL, CONSTRAINT
[PK_SuggestionModelUserModel] PRIMARY KEY ([UserVotesUserId],
[VotedOnSuggestionsSuggestionId]),
CONSTRAINT [FK_SuggestionModelUserModel_Suggestions_VotedOnSuggestionsSuggestionId]
FOREIGN KEY ([VotedOnSuggestionsSuggestionId]) REFERENCES [Suggestions]
([SuggestionId]) ON DELETE CASCADE,
CONSTRAINT [FK_SuggestionModelUserModel_Users_UserVotesUserId] FOREIGN KEY
([UserVotesUserId]) REFERENCES [Users] ([UserId]) ON DELETE CASCADE
);
EDIT I have disabled the Nullable Reference feature in my projects.