![](/img/trans.png)
[英]Entity Framework C# Introducing A Foreign Key X In Table Y May Cause Cycles OR Multiple Cascade Paths
[英]MVC 4 Entity Framework Two Foreign Keys to the Same Table Cause cycles or multiple cascade paths
我有2個實體Unit
和UnitPerUnit
。 他們的角色是:
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
條目被刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.