每个表中的列名必须是唯一的。多次指定表 Entity1' 中的列名'Id'

  • 本文关键字:Id Entity1 唯一 c# .net entity-framework-6
  • 更新时间 :
  • 英文 :


想法是为外键使用名称,因为如果更改属性名称编译器会抓住此问题,所以我永远不会忘记更改外键依赖性

public class Entity1 {
    [Key]
    public int Id { get; set; }
    public int OtherId { get; set; }
    [Foreign Key(nameof(OtherId))]
    public virtual Entity2 Entity { get; set; }
}
   public Entity2 {
    [Key]
    public int Id {get;set;}
    public string Name {get;set;}
}

当我尝试从迁移中更新数据库时,受试者的错误正在遇到。我在这里做错了吗?问候,

您已经在同一类中具有该名称的属性。尝试更改外键名,例如:

[ForeignKey("name of foreign key here")]
  public virtual Entity2 Entity { get; set; }

请参阅:

https://www.entityframeworktoriory.net/code-first/foreignkey-dataannotations-tribute-intribute-in-code-first.aspx

您可以尝试此

public class Entity1 
{
  [Key]
  public int Id { get; set; }
  [ForeignKey("Entity2")]
  public int Entity2ID { get; set; }
  public virtual Entity2 Entity2 { get; set; }
}

最新更新