There are two relationships between the entities “ExpertSystem” and “ExpertiseVariable”. The expert system has many variables of expertise, but it also has a relationship with one of the variables of expertise to indicate that this variable is the target. But when I try to save the expert system to the database, I get an error:
System.InvalidOperationException: “Unable to save changes because a circular dependency was detected in the data to be saved: ‘ExpertSystem [Added] <-
ForeignKeyConstraint { ‘ExpertSystemId’ } ExpertiseVariable [Added] <-
ForeignKeyConstraint { ‘GoalVariableId’ } ExpertSystem [Added]To show additional information call ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’.’.”
public class ExpertSystem
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public List<ExpertiseVariable> ExpertiseVariables { get; set; } = new List<ExpertiseVariable>();
public List<EnvironmentVariable> EnvironmentVariables { get; set; } = new List<EnvironmentVariable>();
public InitializationBlock InitializationBlock { get; set; }
public ExpertiseVariable GoalVariable { get; set; }
public int? GoalVariableId { get; set; }
public CompletionBlock CompletionBlock { get; set; }
public List<VariableBlock> VariableBlocks { get; set; } = new List<VariableBlock>();
}
public class ExpertiseVariable
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public ExpertSystem ExpertSystem { get; set; }
public int ExpertSystemId { get; set; }
public VariableBlock VariableBlock { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ExpertSystem>()
.HasMany(x => x.ExpertiseVariables)
.WithOne(x => x.ExpertSystem)
.HasForeignKey(x => x.ExpertSystemId);
modelBuilder.Entity<ExpertSystem>()
.HasOne(x => x.GoalVariable)
.WithOne()
.HasForeignKey<ExpertSystem>(x => x.GoalVariableId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<ExpertiseVariable>()
.HasOne(x => x.ExpertSystem)
.WithMany(x => x.ExpertiseVariables)
.HasForeignKey(x => x.ExpertSystemId)
.OnDelete(DeleteBehavior.Cascade);
}