Reputation: 695
I have two tables: EstimationActivity and 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; }
}
As you can see there are two foreign keys to the Activity table(class). When I try to add a migration I get:
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.
I tried to restrict all cascade deletions with this, as I found in few articles:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationship.DeleteBehavior = DeleteBehavior.Restrict;
}
base.OnModelCreating(modelBuilder);
}
This didn't do the work. How should I go over the error?
Upvotes: 0
Views: 229
Reputation: 6203
Try use attributes [ForeignKey("SomeId")]
where you set FK's and [InverseProperty("OtherClass")]
overrides this convention and specifies alignment of the properties.
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; }
}
Upvotes: 1