EF迁移生成具有不同名称的重复FK

时间:2016-11-04 16:45:27

标签: entity-framework ef-code-first ef-migrations

我试图重命名默认FK,但是Code First Migration继续使用不同的名称生成第二个FK到同一个表,弄乱了表模式。

FK模型有一个名为Id的PK,我只想保留客户端所需的约定,更改Id(某事物)的名称。

1)生成的迁移:

Generated Migration

2)制图:

Code First Map

我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果您的CorpoGestor实体公开了外键的属性,请使用HasForeignKey代替MapMapKey

HasRequired(x => x.Conselho)
    .WithMany()
    .HasForeignKey(x => x.IdConselho);

另一种解决方案:您可以在属性中使用ForeignKey属性,而不是映射CorpoGestorMap类中的关系:

public class CorpoGestor
{
    ...

    public int IdConselho { get; set; }

    [ForeignKey("IdConselho")]
    public virtual Conselho Conselho { get; set; }
}

警告:在概念上使用实体中的属性并不像在EntityTypeConfiguration映射类中实现代码那么酷,因为您使用应保存在EF类中的数据层代码来污染您的实体。 / p>

相关问题