EntityFramework 核心流利 API

EntityFramework Core Fluent API

我有两个 table:估计值Activity 和 Activity:

public class EstimationActivity 
{
    public Guid Id { get; set; }

    public Guid EstimateId { get; set; }
    public virtual Estimate Estimate { get; set; }

    public Guid ParentActivityId { get; set; }
    public virtual Activity ParentActivity { get; set; }

    public Guid ActivityId { get; set; }
    public virtual Activity Activity { get; set; }

    public double Duration { get; set; }

    [Range(minimum: 0, maximum: 100)]
    public int Contingency { get; set; }

    public ICollection<Note> Notes { get; set; } = new List<Note>();
}

public class Activity
{
    public Guid Id { get; set; }

    public Guid ActivityTypeId { get; set; }
    public virtual ActivityType ActivityType { get; set; }

    public Guid RfcAreaId { get; set; }
    public virtual RfcArea RfcArea { get; set; }

    [Required]
    [StringLength(maximumLength: 60, MinimumLength = 5)]
    public string Name { get; set; }
}

如您所见,Activity table(class) 有两个外键。当我尝试添加迁移时,我得到:

Introducing FOREIGN KEY constraint 'FK_EstimateActivities_Activities_ParentActivityId' on table 'EstimateActivities' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

我试图用它来限制所有级联删除,正如我在几篇文章中发现的那样:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }

        base.OnModelCreating(modelBuilder);
    }

这没有起到作用。我应该如何解决错误?

尝试在设置 FK 的地方使用属性 [ForeignKey("SomeId")][InverseProperty("OtherClass")] 覆盖此约定并指定属性的对齐方式。

    public class EstimationActivity
{
    public Guid Id { get; set; }

    public Guid EstimateId { get; set; }
    public virtual Estimate Estimate { get; set; }

    public Guid ParentActivityId { get; set; }

    [ForeignKey("ParentActivityId")]
    public virtual Activity ParentActivity { get; set; }

    public Guid ActivityId { get; set; }

    [ForeignKey("ActivityId")]
    public virtual Activity Activity { get; set; }

    public double Duration { get; set; }

    [Range(minimum: 0, maximum: 100)]
    public int Contingency { get; set; }

    public ICollection<Note> Notes { get; set; } = new List<Note>();
}

public class Activity
{
    public Guid Id { get; set; }

    public Guid ActivityTypeId { get; set; }
    public virtual ActivityType ActivityType { get; set; }

    public Guid RfcAreaId { get; set; }
    public virtual RfcArea RfcArea { get; set; }

    [Required]
    [StringLength(maximumLength: 60, MinimumLength = 5)]
    public string Name { get; set; }


    [InverseProperty("ParentActivity")]
    public virtual EstimationActivity EstimationParentActivity { get; set; }
    [InverseProperty("Activity")]
    public virtual EstimationActivity EstimationActivity { get; set; }
}