簡體   English   中英

MVC 4實體框架同一表的兩個外鍵導致循環或多個級聯路徑

[英]MVC 4 Entity Framework Two Foreign Keys to the Same Table Cause cycles or multiple cascade paths

我有2個實體UnitUnitPerUnit 他們的角色是:

  • Unit :定義單位,例如公斤,米,厘米,碼等。
  • UnitPerUnit :保存單位之間的值(例如:1kg = 1000gr)

這是代碼:

[Table("EA_Unit", Schema = "EAccounting")]
public class EA_Unit
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Unit Id")]
    public int UnitId { get; set; }

    [Display(Name = "Unit Name")]
    [Index("UnitName", IsUnique = true)]
    [MaxLength(20)]
    [Required]
    public string UnitName { get; set; } //Example kg, piece, roll, yard, meter

    public EA_Unit()
    {
        UnitName = "";
    }
}

[Table("EA_UnitPerUnit", Schema = "EAccounting")]
public class EA_UnitPerUnit
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name = "Unit Per Unit Id")]
    public int UnitPerUnitId { get; set; }

    [Display(Name = "From Unit")]
    [Required]
    [Index("UnitToUnit", 1, IsUnique = true)]
    public int UnitId { get; set; }

    [Display(Name = "To Name")]
    [Required]
    [Index("UnitToUnit", 2, IsUnique = true)]
    public int UnitToUnit { get; set; } //The comparer unit

    [Display(Name = "Amount")]
    [Required]
    public float UnitAmount { get; set; } //how much is this unit to another unit (ex: 1kg = 1000gr)

    [ForeignKey("UnitId")]
    public virtual EA_Unit Unit { get; set; }

    [ForeignKey("UnitToUnit")]
    public virtual EA_Unit UnitTo { get; set; }

    public EA_UnitPerUnit()
    {
        UnitId = 0;
        UnitToUnit = 0;
        UnitAmount = 0;
    }
}

每當我運行程序並創建數據庫時,就會出現此錯誤:

在表'EA_UnitPerUnit'上引入FOREIGN KEY約束'FK_EAccounting.EA_UnitPerUnit_EAccounting.EA_Unit_UnitToUnit'可能會導致循環或多個級聯路徑。 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。 無法創建約束。 請參閱先前的錯誤。

我想要的是,如果刪除了Unit ,則在UnitPerUnit public virtual EA_Unit Unit { get; set; }中保存該已刪除Unit的值的UnitPerUnit條目public virtual EA_Unit Unit { get; set; } public virtual EA_Unit Unit { get; set; } public virtual EA_Unit Unit { get; set; }public virtual EA_Unit UnitTo { get; set; } public virtual EA_Unit UnitTo { get; set; } public virtual EA_Unit UnitTo { get; set; }也將被刪除。

我該如何克服這個問題? 我想設置數據庫這樣的數據庫會自動刪除UnitPerUnit后進入Unit條目被刪除。

此問題已得到一次又一次的解決。 請參考此答案

具有級聯刪除功能的外鍵意味着,如果刪除父表中的記錄,則子表中的相應記錄將被自動刪除。 這在SQL Server中稱為級聯刪除。

參考鏈接

您將需要使用模型構建器來解決此問題。

modelBuilder.Entity<...>()
            .HasRequired(...)
            .WithMany(...)
            .HasForeignKey(...)
            .WillCascadeOnDelete(false);

要么

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM