【问题标题】:Why does Entity Framework create a redundant foreign key?为什么实体框架会创建冗余外键?
【发布时间】:2017-02-26 19:55:27
【问题描述】:

我有这 3 个课程:

public class P
{
    [Key]
    [Column(Order = 0)]
    [Required]
    public string PId { get; set; }
}

public class E
{
    [Key]
    [ForeignKey("P")]
    [Column(Order = 0)]
    [Required]
    public string PId { get; set; }

    [Key]
    [Column(Order = 1)]
    [Required]
    public string EId { get; set; 
}

public class UF
{
    [Key]
    [Required]
    public string Id { get; set; }

    [ForeignKey("E")]
    [Column(Order = 0)]
    public string PId { get; set; }


    [ForeignKey("E")]
    [Column(Order = 1)]
    public string EId { get; set; }
}

当运行实体框架代码优先时,我希望在数据库中得到类似的东西:

但我得到的是上述 + 额外的 FK 到 PId:

即在 CREATE SCRIPT 我们得到:

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_dbo.UF_dbo.E_PId_EId]') AND parent_object_id = OBJECT_ID(N'[dbo].[UF]'))
ALTER TABLE [dbo].[UF] WITH CHECK 
     ADD CONSTRAINT [FK_dbo.UF_dbo.E_PId_EId] 
     FOREIGN KEY([PId], [EId]) REFERENCES [dbo].[E] ([PId], [EId])
          ON DELETE CASCADE
GO

但我们也得到了这个额外/冗余的 FK:

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_dbo.UF_dbo.P_PId]') AND parent_object_id = OBJECT_ID(N'[dbo].[UF]'))
ALTER TABLE [dbo].[UF] WITH CHECK 
    ADD CONSTRAINT [FK_dbo.UF_dbo.P_PId] 
    FOREIGN KEY([PId]) REFERENCES [dbo].[P] ([PId])
         ON DELETE CASCADE
GO

运行整个 CREATE SCRIPT 时会导致此错误:

在表“UF”上引入 FOREIGN KEY 约束“FK_dbo.UF_dbo.P_PId”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。

消息 1750,第 16 级,状态 0,第 926 行
无法创建约束或索引。查看以前的错误。

问题是为什么?

【问题讨论】:

  • 在添加导航属性 EP(我希望这不是您真正要使用的名称)后,可以与 EF6 一起使用。这是哪个版本?

标签: sql entity-framework ef-code-first foreign-keys code-first


【解决方案1】:

您的身份证件名称不正确。 像这样重命名您的ID:

pubilc class P
{
    public string Id { get; set; }
}

public class E
{
    public string PId { get; set; }
//Entity Framework automatically recognizes it is a foreign key for P Table.

    public string Id { get; set; }
//don't use EId , For Primary Key just use Id.
}

public class UF
{
    public string Id { get; set; }

    public string PId { get; set; }

    public string EId { get; set; }
//For Foreign key just use: ClassName + Id
}

【讨论】:

    【解决方案2】:

    很遗憾,答案不在问题描述中:/

    有一个额外的虚拟成员 P 导致了额外的 FK:

        //Shouldn't be here
        public virtual P P { get; set; }
    
        public virtual E E { get; set; }
    

    是啊是啊……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多