为外键生成的名称将覆盖现有列名

时间:2015-03-23 20:58:32

标签: entity-framework

我正在使用Code First EF v6.0。我有一个表MyTable,它应该有3列: Id(私钥),Name和OtherTable_Name(外键)。

[Key]
public int Id { get; set; }

[Index(IsUnique = true)]
[MaxLength(400)]
public string Name { get; private set; } 

public virtual OtherTable ARandomStringName { get; set; }

我遇到了一个奇怪的错误,其中Name填充了OtherTable_Name的值,并且没有生成外键。 我将OtherTable的私钥重命名为OtherTableName。现在我得到一个包含Id,Name和OtherTable_OtherTableName的数据库表。

这解决了我的直接问题 - 缺少外键,错误的名称值 - 但我不明白为什么它首先发生。 (我宁愿能够合理地将该字段称为OtherTable.Name,而不是OtherTable.OtherTableName。)

EF何时使用OtherTable_作为外键列名称的前缀,何时不是?这两个表都有" Id"作为私钥列 - 与一个表中的私钥而不是另一个表中的字段有什么关系?我该怎么做才能避免在其他地方发生这种错误?

1 个答案:

答案 0 :(得分:0)

您可以使用DataAnnotations覆盖EF约定。确保您有

的参考
using System.ComponentModel.DataAnnotations

然后只需将ForeignKey属性添加到NavigationProperty

即可
public int OtherTableId { get; set; }

[ForeignKey("OtherTableId")]
public virtual OtherTable OtherTableItem { get; set; }