我有三个实体:
ApplicationUser:
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
有很多MeetingNotification
MeetingNotification
有一个ApplicationUser
和一个Meeting
Meeting
有很多MeetingNotification
当我尝试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);
...错误消失了!但是我不完全理解为什么,所以任何好的解释都将不胜感激!