我想在EF Core的TBH(每个层次的表)中使用最佳外键。我尝试了许多解决方案,但没有一个起作用。我想在删除其他实体时将外键设置为null。在我的代码中,这意味着我想在删除FriendRequest
时将FriendRequestNotification
中的FriendRequest
设置为空。
我总是收到此错误:
Npgsql.PostgresException:23503:表“ FriendRequests”上的更新或删除违反了表“ Notifications”上的外键约束“ FK_Notifications_FriendRequests_FriendRequestId”
DbContext
public class HankContext : DbContext
{
public virtual DbSet<Notification> Notifications { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Notification>()
.HasDiscriminator<NotificationType>("Type")
.HasValue<FriendRequestNotification>(NotificationType.FriendRequest)
.HasValue<FriendAcceptNotification>(NotificationType.AcceptedFriend);
//this part is the one which I thought would solve the problem
builder.Entity<FriendRequest>()
.HasOne<FriendRequestNotification>()
.WithOne(x => x.FriendRequest)
.IsRequired(false)
.OnDelete(DeleteBehavior.SetNull);
}
}
FriendRequestNotification
public class FriendRequestNotification : Notification
{
public Guid? FriendRequestId { get; set; }
public virtual FriendRequest FriendRequest { get; set; }
}
通知
public abstract class Notification
{
public Guid Id { get; set; }
[Required]
public NotificationType Type { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public User Receiver { get; set; }
[Required]
public bool IsRead { get; set; }
}
如何实现上述外键设置为null?谢谢您的帮助。