【问题标题】:Error: Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?错误:引入 FOREIGN KEY 约束可能会导致循环或多个级联路径 - 为什么?
【发布时间】:2017-01-26 01:59:49
【问题描述】:

我有很多课程,但在PorductionLineMachine 我有一些问题。生产线类是:

[Column("FldKeyId")]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   [Required]
   [Key]
   public int MyKeyId { get; set; }
   [Column("FldCode")]
    [Required]
   [Index(IsUnique = true)]
   public int MyCode
   {
       get { return _Code; }
       set { _Code = value; }
   }
   [Column("FldName")]
    [Required]
   public string MyName
   {
       get { return _Name; }
       set { _Name = value; }
   }
   [Column("FldLocation")]
    [Required]
   public string MyLocation
   {
       get { return _Location; }
       set { _Location = value; }
   }

   [Column("FldCompanyKey")]
   public int MyCompanyKey { get; set; }
   [ForeignKey("MyCompanyKey")]
    [Required]
   public virtual Company Company { get; set; }

而机器类是:

[Column("FldKeyId")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    [Key]
    public int MyKeyId { get; set; }
    [Column("FldCode")]
    [Required]
    [Index(IsUnique = true)]
    public int MyMachineCode
    {
        get { return _MachineCode; }
        set { _MachineCode = value; }
    }
    [Column("FldName")]
    [Required]
    public string MyName
    {
        get { return _Name; }
        set { _Name = value; }
    }

    [Column("FldProductionLineKey")]

    public int MyProductionLineKey { get; set; }
    [ForeignKey("MyProductionLineKey")]
    //[Required]
    public ProductionLine ProductionLine { get; set; }

当我想从这些类中生成数据库时,我遇到了这个错误:

引入 FOREIGN KEY 约束 'FK_dbo.TblMachine_dbo.TblProductionLine_FldProductionLineKey' on 表 'TblMachine' 可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN 关键约束。

无法创建约束或索引。请参阅以前的错误。 当我评论这 3 行时

[Column("FldProductionLineKey")]
public int MyProductionLineKey { get; set; }
[ForeignKey("MyProductionLineKey")]

错误消失了,但我想要这个代码在其他一些类中我有这个问题...... 我必须做什么? 感谢您的帮助!

【问题讨论】:

    标签: c# ef-code-first


    【解决方案1】:

    您收到此错误消息是因为在 SQL Server 中,表不能 在所有级联引用的列表中出现多次 由 DELETE 或 UPDATE 语句启动的操作。 例如,级联引用操作的树必须只有 级联引用操作上特定表的一条路径 树。

    您可以将 cascadeDelete 设置为 false 或 true(在您的迁移 Up() 方法中)。取决于你的要求。

    AddForeignKey(..., cascadeDelete: false);
    

    更多信息请查看this question

    【讨论】:

    • 好吧,它曾经工作过,但它是一个业务程序,在客户系统中,我想要带有 database.CreateIfNotExist 的板条箱数据库是属性或类似的东西,我把它放在我的班级中,作为 cascadeDelete: false
    • @sadeq 你可以在流畅的映射中做到这一点
    猜你喜欢
    • 2013-06-12
    • 2018-08-08
    • 2011-05-08
    • 2013-10-22
    相关资源
    最近更新 更多