【问题标题】:Can't get property names working with foreign keys in Code First无法在 Code First 中使用外键获取属性名称
【发布时间】:2014-04-02 22:20:42
【问题描述】:

我得到了一个数据库,我需要为它设置 Code First。我想我已经完成了,我现在遇到的问题是我想更改实体中的一些外键名称以使其更有意义。

假设我有两张表,Person 和 Location,看起来像这样:

Person
------
PersonId int not null (PK)
DefaultLocation int not null (FK)


Location
--------
LocationId int not null (PK)

对于位置实体,我想我知道了:

public class Location
{
    [Key]
    public int LocationId { get; set; }

    [InverseProperty("DefaultLocation")]
    public List<Person> PeopleWithDefault { get; set; }
}

现在,我想要在我的 Person 实体上拥有 2 个属性,一个 DefaultLocation 导航属性和一个用于外键的 DefaultLocationId 属性。这就是我现在所处的位置:

public class Person
{
    [Key]
    public int PersonId { get; set; }

    [ForeignKey("Location")]
    [Column("DefaultLocation")]
    [Required]
    public int DefaultLocationId { get; set; }

    public virtual Location DefaultLocation { get; set; }
}

这是哪个坏孩子扔的:

类型“Person”的属性“DefaultLocationId”上的 ForeignKeyAttribute 无效。在依赖类型“人员”上找不到导航属性“位置”。 Name 值应该是有效的导航属性名称。

所以,这个错误非常有意义......我只是不知道如何修复它。我显然在某处遗漏了注释,或者错误地使用了 [ForeignKey]。谁能帮帮我?

【问题讨论】:

    标签: c# entity-framework ef-code-first code-first


    【解决方案1】:

    将FK属性中的字符串改为属性名,而不是类型名:[ForeignKey("DefaultLocation")]

    【讨论】:

      【解决方案2】:

      我也遇到了类似的问题。 在下面查看我的课程

      作者是父表

      public class Author
          {
              [Key]
              public int AuthorID { get; set; }
              [Required]
              public string Name { get; set; }
          }
      

      图书的外键是 AuthorID

      public class Book
          {
              [Key]
              public int BookId { get; set; }
              [Required]
              public string Title { get; set; }
              public decimal Price { get; set; }
              public string Genre { get; set; }
              public DateTime PublishDate { get; set; }
              public string Description { get; set; }
              public int AuthorID { get; set; }
              [ForeignKey("AuthorID")]
              public virtual Author Author { get; set; }
          }
      

      我刚刚更新了我的代码并在下面添加了虚拟

      [ForeignKey("AuthorID")]
       public virtual Author Author { get; set; }
      

      所以基本上在书中我与作者拥有相同的属性

      public int AuthorID { get; set; }
      

      还有一个 Author 类型的虚拟属性

      [ForeignKey("AuthorID")]
       public virtual Author Author { get; set; }
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-18
        • 1970-01-01
        • 2013-10-21
        • 1970-01-01
        • 2014-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多