Hi I have MVC 6 application with Entity Framework Core 1.0 RTM and SQL server, when I try to generate database tables, I got "Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths" error.
My model classes are as below:
Category Model:
public class Category
{
public Category()
{
this.VariableSettings = new List<VariableSetting>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public List<VariableSetting> VariableSettings { get; set; }
public List<Station> Stations { get; set; }
}
Station Model:
public class Station
{
public int StationId { get; set; }
public string StationName { get; set; }
public double? Longitude { get; set; }
public double? Latitude { get; set; }
public List<VariableRecord> VariableRecords { get; set; }
public int CategoryID { get; set; }
public Category Category { get; set; }
}
VariableRecord Model:
public class VariableRecord
{
[Key]
public int VariableRecordId { get; set; }
public double Value { get; set; }
public DateTime RecordDate { get; set; }
public int StationId { get; set; }
public Station Station { get; set; }
public int VarSettingId{ get; set; }
public virtual VariableSetting VariableSetting { get; set; }
}
VariableSetting Model:
public class VariableSetting
{
[Key]
public int VarSettingId { get; set; }
public int Sequence { get; set; }
public double? MinimumValue { get; set; }
public double? MaximumValue { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public int VariableId { get; set; }
public Variable Variable { get; set; }
public List<VariableRecord> VariableRecords { get; set; }
}
Variable Model:
public class Variable
{
public int VariableId { get; set; }
public string VariableName { get; set; }
public string Description { get; set; }
public string Unit { get; set; }
public List<VariableSetting> VariableSettings { get; set; }
}
So, there are too Cascade delete routes in my codes Category->Station->VariableRecord and Category->VariableSetting->VariableRecord, so I am trying to diable the route Category->VariableSetting->VariableRecord in the context class with Fluent API as below:
builder.Entity<VariableRecord>()
.HasOne(pt => pt.VariableSetting)
.WithMany(p => p.VariableRecords)
.HasForeignKey(pt => pt.VarSettingId)
.OnDelete(DeleteBehavior.Cascade);
However I still got same as below:
System.Data.SqlClient.SqlException (0x80131904): Introducing FOREIGN KEY constraint 'FK_VariableSetting_Category_CategoryId' on table 'VariableSetting' may cause cycles or multiple cascade paths.Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I have been stuck on these codes for couple of days but still went nowhere, please help!
Use DeleteBehavior.Restrict
instead of DeleteBehavior.Cascade
.
You already have multiple cascade path, so if you want (ok, you need) disable cascading on one of them - use DeleteBehavior.Restrict
.