为什么Entity Framework会创建冗余外键?

时间:2017-02-26 19:55:27

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

我有这三个班级:

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; }
}

首先运行Entity Framework代码时,我希望在数据库中得到类似的内容:

enter image description here

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

enter image description here

即。在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时会导致此错误:

  

介绍FOREIGN KEY约束' FK_dbo.UF_dbo.P_PId'在桌子上' UF'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

     

Msg 1750,Level 16,State 0,Line 926
  无法创建约束或索引。查看以前的错误。

问题是为什么?

2 个答案:

答案 0 :(得分:0)

您的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
}

答案 1 :(得分:0)

不幸的是,答案不在问题描述中:/

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

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

    public virtual E E { get; set; }

是啊是啊......