数据注解不会创建一对多的对象引用

Data annotations not create one-to-many object references

我在使用数据注释时遗漏了一些东西。

这是我的第一个class

[Table("PriceFeed")]
public class PriceFeed : History
{
    public PriceFeed()
    {
        this.Votes = new List<PriceVote>();
        this.History = new List<PriceFeed__History>();
    }

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

    [ForeignKey("Store")]
    public long Store_Id { get; set; }

    [ForeignKey("Item")]
    public long Item_Id { get; set; }

    [Required]
    public decimal Price { get; set; }

    public Store Store { get; set; }

    public Item Item { get; set; }

    public virtual ICollection<PriceFeed__History> History { get; set; }

}

这是我的第二个 class

[Table("PriceFeed__History")]
public class PriceFeed__History : History
{

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

    [ForeignKey("PriceFeed")]
    public long PriceFeed_Id { get; set; }

    [Required]
    public decimal Price { get; set; }

    public virtual PriceFeed PriceFeed { get; set; }

}

当我 运行 添加迁移时,它正确地创建了数据库,但是当我尝试访问 PriceFeed.History 时它给我一个错误

{"Message":"An error has occurred.","ExceptionMessage":"A specified Include path is not valid. The EntityType 'Verdinhas.Web.Contexts.PriceFeed' does not declare a navigation property with the name 'PriceFeed__History'."

我一直用 API 流利地工作,并且自己输入

这样的代码
.Entity<Student>()
                .HasRequired<Standard>(s => s.Standard)
                .WithMany(s => s.Students)
                .HasForeignKey(s => s.StdId);

但现在我正在使用数据注释,当我生成迁移时,它不会像上面那样创建 "withmany"。

我做错了什么?

这个问题与数据注释无关,它在您的模型中似乎是正确的。

如评论中所述,异常是由尝试将 Include 方法与 string "'PriceFeed__History" 一起使用的代码引起的 - 你似乎认为你应该指定相关实体 types,但实际上您需要指定导航 属性 names,在您的例子中是 "History".