【问题标题】:Code First Cascade Delete Not Using Fluent API代码优先级联删除不使用 Fluent API
【发布时间】:2013-03-18 22:46:42
【问题描述】:

我有这两个实体

class AUT
{
    public Guid ID { get; set; }
    public string Name { get; set; }

    public Engineer Engineer { get; set; }
}

class InstallationSetup
{
    public virtual AUT ApplicationUnderTesting { get; set; }

    public Guid ID { get; set; }
    // Loads of properties etc
}

class Engineer
{
    public Guid ID { get; set; }
    public string Name { get; set; }
}

首先使用代码和一些数据注释,这些实体创建了一个数据库。我正在使用 EF 5,当我删除一个应用程序时,它应该只删除它自己和任何引用它的 InstallationSetup。它不应该删除工程师。但是,当我尝试删除它时,我得到了错误:

DELETE 语句与 REFERENCE 约束“FK_dbo.InstallationSetups_dbo.AUTs_ApplicationUnderTesting_ID”冲突。冲突发生在数据库“UXLab”、表“dbo.InstallationSetups”、列“ApplicationUnderTesting_ID”中。 声明已终止。

所以,我猜是因为有另一个表的条目依赖于 AUT,所以通过删除 AUT,您将留下带有空外键的 InstallationSetup,从而导致行损坏。

我应该能够(最好不使用 Fluent API)告诉实体框架任何引用 AUT 的东西也应该被删除?这就是我想要达到的目标。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework


    【解决方案1】:

    您只需添加一个与您生成的外键列相似的列,当实体框架生成此 FK 列时,它会将级联删除设置为禁用。

    class AUT
    {
       public Guid ID { get; set; }
       public string Name { get; set; }
    
      public Engineer Engineer { get; set; }
    }
    
    class InstallationSetup
    {
        public virtual AUT ApplicationUnderTesting { get; set; }
        public int ApplicationUnderTestingId {get; set;}   <--- Add this.
    
       public Guid ID { get; set; }
    // Loads of properties etc
    }
    
    class Engineer
    {
     public Guid ID { get; set; }
     public string Name { get; set; }
    }
    

    如果你再次生成你的数据库,你会发现有些东西发生了变化。自动生成的 AUTs_ApplicationUnderTesting_ID 列不再存在,ApplicationUnderTestingId 列现在用于您的外键关系。

    EF 现在将自动启用级联删除。

    【讨论】:

    • 关于将实体添加到数据库中,我现在是否必须用相对 ID 填写新属性而不是填写 AUT 属性,还是我都填写了它们?
    • 只需填写相对Id EF会自动映射到所需的实体。
    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多