I have three entities:
ApplicationUser:
public class ApplicationUser : IdentityUser<Guid>
{
// more properties
public List<MeetingNotification> MeetingNotifications { get; set; }
}
MeetingNotifications:
public class MeetingNotification
{
public Guid Id { get; set; }
public Guid MeetingId { get; set; }
public Meeting Meeting { get; set; }
public Guid SummonedUserId { get; set; }
public ApplicationUser SummonedUser { get; set; }
}
Meetings:
public class Meeting
{
public Guid Id { get; set; }
// more properties
public Guid OrganizerId { get; set; }
public ApplicationUser Organizer { get; set; }
public List<MeetingNotification> Notifications { get; set; }
}
The relationships are as such:
- One
ApplicationUser
has manyMeetingNotification
s - One
MeetingNotification
has oneApplicationUser
and oneMeeting
- One
Meeting
has manyMeetingNotification
s
When I try to update-database
, I get the error message
Introducing FOREIGN KEY constraint 'FK_MeetingNotifications_Meetings_MeetingId' on table 'MeetingNotifications' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
This error is my arch nemesis, as I struggle to understand were the error lies. Is it in Meeting
or in MeetingNotification
. Or somewhere else?
I have tried these three definitions:
modelBuilder.Entity<MeetingNotification>()
.HasOne(m => m.Meeting)
.WithMany(n => n.Notifications)
.HasForeignKey(fk => fk.Id).OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<MeetingNotification>()
.HasOne(m => m.Meeting)
.WithMany(n => n.Notifications)
.HasForeignKey(fk => fk.MeetingId).OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<Meeting>()
.HasMany(n => n.Notifications)
.WithOne(m => m.Meeting)
.HasForeignKey(fk => fk.MeetingId).OnDelete(DeleteBehavior.NoAction);
... but they don't seem to do anything. It's just the same error message every time
Update
I finally found a way!
modelBuilder.Entity<MeetingNotification>()
.HasOne(m => m.Meeting)
.WithMany(n => n.Notifications)
.OnDelete(DeleteBehavior.Restrict);
... and the error went away! But I don't fully understand why, so any good explanation would be appreciated!