如何在Entity Framework Core 1.0 RTM中關閉級聯刪除

asp.net-core-mvc c# entity-framework entity-framework-core sql

嗨我有實體框架核心1.0 RTM和SQL服務器的MVC 6應用程序,當我嘗試生成數據庫表時,我得到“引入FOREIGN KEY約束可能導致循環或多個級​​聯路徑”錯誤。

我的模型類如下:

分類型號:

 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; }
}

站型號:

 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模型:

 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; }
}

變量設置模型:

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; }
}

變量模型:

 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; }
}

所以,在我的代碼Category-> Station-> VariableRecord和Category-> VariableSetting-> VariableRecord中也有Cascade刪除路由,所以我試圖在Fluent API中將上下文類中的路徑Category-> VariableSetting-> VariableRecord調整為下面:

builder.Entity<VariableRecord>()
        .HasOne(pt => pt.VariableSetting)
        .WithMany(p => p.VariableRecords)
        .HasForeignKey(pt => pt.VarSettingId)
        .OnDelete(DeleteBehavior.Cascade);

但是我仍然如下:

System.Data.SqlClient.SqlException(0x80131904):在表'VariableSetting'上引入FOREIGN KEY約束'FK_VariableSetting_Category_CategoryId'可能會導致循環或多個級​​聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。

我被困在這些代碼上幾天但仍然無處可去,請幫忙!

熱門答案

使用DeleteBehavior.Restrict而不是DeleteBehavior.Cascade

您已經有多個級聯路徑,因此如果您需要(確定,您需要)在其中一個上禁用級聯 - 請使用DeleteBehavior.Restrict



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow