I have issues solving the following error in EF Core.
Introducing FOREIGN KEY constraint FK_EventParticipant_Events_EventId
on table EventParticipant
may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index.
Here are my models:
public class Event
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(20, MinimumLength = 5)]
public string Name { get; set; } = null!;
[Required]
[StringLength(150, MinimumLength = 15)]
public string Description { get; set; } = null!;
[Required]
public string OrganiserId { get; set; } = null!;
[Required]
[ForeignKey(nameof(OrganiserId))]
public IdentityUser Organiser { get; set; } = null!;
[Required]
public DateTime CreatedOn { get; set; }
[Required]
public int TypeId { get; set; }
[Required]
[ForeignKey(nameof(TypeId))]
public Models.Type Type { get; set; } = null!;
public ICollection<EventParticipant> EventsParticipants = new List<EventParticipant>();
}
public class Type
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(15, MinimumLength = 5)]
public string Name { get; set; } = null!;
public ICollection<Event> Events { get; set; } = new List<Event>();
}
public class EventParticipant
{
public string HelperId { get; set; } = null!;
[ForeignKey(nameof(HelperId))]
public IdentityUser Helper { get; set; } = null!;
public int EventId { get; set; }
[ForeignKey(nameof(EventId))]
public Event Event { get; set; } = null!;
}
If I understand correctly, the main issue here (with this exception in general) is what happens if we delete, for example, an event in the context of my data models. Do all of the event participant entries with that event id in the database get deleted as well? Doesn't the same apply if we delete an IdentityUser from the database? Do we accordingly delete the records from the EventParticipant table?
I can't exactly figure out what's the problem if we delete an event. If we have a record in the table EventParticipant with the deleted event Id, won't the EventId column actually hold the id of the deleted event and won't we have a reference to the deleted event in the Event
property?
What am I supposed to configure for everything to work correctly?
P.P. This seems to work in the OnModelCreating override method, but I am not really sure what's happening.
modelBuilder.Entity<EventParticipant>()
.HasOne(e => e.Event)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);