无法对自联接多对多关系创建外键约束

时间:2018-08-13 19:34:25

标签: ef-core-2.0

我创建了以下课程:

public class Character
{
    public int ID { get; set; }
    public string Title { get; set; }

    public ICollection<Relationship> RelatedTo { get; set; }
    public ICollection<Relationship> RelatedFrom { get; set; }
}

public class Relationship
{
    public int ToID { get; set; }
    public int FromID { get; set; }

    public Character CharacterFrom { get; set; }
    public Character CharacterTo { get; set; }

    public string Details { get; set; }
}

在我的上下文中,我有这个:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Relationship>()
            .HasKey(r => new { r.ToID, r.FromID });

        modelBuilder.Entity<Relationship>()
            .HasOne(r => r.CharacterFrom)
            .WithMany(r => r.RelatedTo)
            .HasForeignKey(r => r.FromID)
            .OnDelete(DeleteBehavior.ClientSetNull);

        modelBuilder.Entity<Relationship>()
            .HasOne(r => r.CharacterTo)
            .WithMany(r => r.RelatedFrom)
            .HasForeignKey(r => r.ToID)
            .OnDelete(DeleteBehavior.ClientSetNull);
    }

认为正确,但是由于以下错误,我无法应用迁移:

Cannot create the foreign key "FK_Relationship_Character_FromID" with the SET NULL referential action, because one or more referencing columns are not nullable.

我为OnDelete尝试了 DeleteBehaviour 的每种组合。他们都不工作。我不相信我可以使ICollections可为空,而且我想这样做似乎不正确。我已经花了两个小时来寻找答案。我尝试遵循的每篇关于EF Core的教程或解释似乎都采用了稍微不同的方法,并且彼此之间微妙地不兼容。请帮忙!

1 个答案:

答案 0 :(得分:1)

错误告诉您不能使用DeleteBehavior.ClientSetNull(或DeleteBehavior.SetNull),因为相应的FK属性不可为空-ToIDFromID的类型均为{ {1}},因此不允许设置为int (客户端和服务器均不允许)。

要为必需的 FK关系关闭级联删除(以打破我猜的多个级联路径),请改用null