【问题标题】:'PK_dbo.EntityName' is not a constraint. Could not drop constraint.EF6'PK_dbo.EntityName' 不是约束。无法删除约束。EF6
【发布时间】:2016-12-27 18:08:00
【问题描述】:

我首先使用的是 Entity Framework 6 代码。我有三个这样的实体:

public class Doctor
{
    public string DoctorID { get; set; } 
    public string firstName { get; set; }
    public string lastName { get; set; }
 }

public class ExpertiseDetails
{
    [Key, Column(Order = 1)]
    public short expertiseID { get; set; }
    [Key , Column(Order = 2)]
    public string DoctorID { get; set; }

    [ForeignKey("expertiseID")]
    public Expertise expertise { get; set; }
    public Doctor doctor { get; set; }
}


public class Expertise
{
    [Key]
    public short expertiseID { get; set; }
    public string expertiseTitle { get; set; }
}

我需要ExpertiseDoctor 之间的one to many 关系,当我在控制台nuGet 中运行更新数据库语句时,此错误显示:

'PK_dbo.ExpertiseDetails' is not a constraint. Could not drop constraint

怎么了?

【问题讨论】:

  • 我认为您的数据库中有数据,请删除数据并重试
  • @Moein 。我尝试了你的建议,但它不起作用!

标签: c# entity-framework-6 code-first


【解决方案1】:

重命名表架构后遇到类似问题,我通过使用 sql 显式删除 PK 名称来解决。

在我的情况下,当重命名表架构后更改表中的主键时出现问题:

原文:

  • dbo.LogEntries PK 名称:PK_dbo.LogEntries

第 1 步:架构更改:

  • PK 不变的 Logging.LogEntries

第二步:PK变化

  • PK 已更改:结果为 DropPrimaryKey("Logging.LogEntries");

最后一行转换为 PK 名称:PK_Logging.LogEntries,它不存在。

修复: 一般来说,有几种方法可以解决这个问题。我在显式迁移中通过 sql 语句删除了 PK。

Sql("ALTER TABLE [Logging].[LogEntries] DROP CONSTRAINT [PK_dbo.LogEntries]");

被告知;我拥有完整的生产访问权限,以防万一它失败并且没有使用迁移回滚到以前的状态。

【讨论】:

    【解决方案2】:

    here 所述,默认名称可能与您的数据库不匹配。在这种情况下,文档说要手动修改迁移文件(UpDown 方法)以使用 name 参数,这将覆盖主键或外键(或其他数据库对象)的默认名称视情况而定)。

    例如,对我来说,生成的行:

    DropPrimaryKey("dbo.MyTable");
    

    变成:

    DropPrimaryKey("dbo.MyTable", "PK_MyTable");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多