![](/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.