0

我有三个实体:

应用用户:

public class ApplicationUser : IdentityUser<Guid>
{
    // more properties
    public List<MeetingNotification> MeetingNotifications { get; set; }
}

会议通知:

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; }
}

会议:

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; }
}

关系是这样的:

  • 一个ApplicationUser有很多MeetingNotifications
  • 一个MeetingNotification有一个ApplicationUser和一个Meeting
  • 一个Meeting有很多MeetingNotifications

当我尝试时update-database,我收到错误消息

在表“MeetingNotifications”上引入 FOREIGN KEY 约束“FK_MeetingNotifications_Meetings_MeetingId”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。

这个错误是我的主要克星,因为我很难理解错误所在。是在Meeting还是在MeetingNotification。或者别的地方?

我试过这三个定义:

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);

...但他们似乎什么也没做。每次都是一样的错误信息

更新

我终于找到了办法!

modelBuilder.Entity<MeetingNotification>()
    .HasOne(m => m.Meeting)
    .WithMany(n => n.Notifications)
    .OnDelete(DeleteBehavior.Restrict);

...并且错误消失了!但我不完全明白为什么,所以任何好的解释都将不胜感激!

4

0 回答 0