【问题标题】:Foreign key property not valid? (Entity framework code first) [duplicate]外键属性无效? (实体框架代码优先)[重复]
【发布时间】:2016-10-05 18:18:24
【问题描述】:

我首先使用实体​​框架代码并添加了一个具有类列表的类,这些类还必须具有另一个类列表,但是当我尝试通过迁移对数据库进行更新时,我得到了这个:

SubscaleScore 类型的属性“SubscaleStatistics”上的 ForeignKeyAttribute 无效。在依赖类型“SubscaleScore”上找不到外键名称“SubscaleStatisticsId”。 Name 值应该是一个逗号分隔的外键属性名称列表。

这是我的课程的样子:

public class ExamStatistics : StatisticsData
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public int TestId { get; set; }
    public IList<SubscaleStatistics> Subscales { get; set; }
}

public class SubscaleStatistics
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int SubscaleStatisticsId { get; set; }
    public int TestId { get; set; }
    public int SubscaleNumber { get; set; }
    public int ExamStatisticsId { get; set; }

    [ForeignKey("ExamStatisticsId")]
    public virtual ExamStatistics ExamStatistics { get; set; }

    public IList<SubscaleScore> SubscaleScores { get; set; }
}

public class SubscaleScore
{
    public int TestId { get; set; }
    public int Subscale { get; set; }
    public double Score { get; set; }
    public int SubscaleId { get; set; }

    [ForeignKey("SubscaleStatisticsId")]
    public virtual SubscaleStatistics SubscaleStatistics { get; set; }

}

我在这里做错了什么?还是我需要提供更多信息才能找出问题所在?

【问题讨论】:

  • 您是否尝试将SubscaleStatisticsId 属性添加到SubscaleScore 类作为错误状态?

标签: c# .net entity-framework ef-code-first entity-framework-migrations


【解决方案1】:

您需要将外键属性添加到 SubscaleScore。

public int SubscaleStatisticsId { get; set; }

教程见这里:foreign keys

【讨论】:

    【解决方案2】:

    外键必须是 id 而不是对象

    试试这样的:

    public class SubscaleScore
    {
        public int TestId { get; set; }
        public int Subscale { get; set; }
        public double Score { get; set; }
        public int SubscaleId { get; set; }
    
        [ForeignKey("SubscaleStatisticsId")]
        public int SubscaleStatisticsId { get; set; }
    
        public virtual SubscaleStatistics SubscaleStatistics { get; set; }
    
    }
    

    对所有带有外键的类都做同样的事情

    【讨论】:

      猜你喜欢
      • 2011-08-05
      • 2012-05-10
      • 2015-02-24
      • 2021-01-05
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多