1

我有一个类,我用它来存储不同赛季的球员统计数据

public class PlayerModel
{
    public int PlayerID { get; set; }
    public Dictionary<int, SeasonStats> SeasonStats { get; set; }

    public PlayerModel()
    {
        this.SeasonStats = new Dictionary<int, SeasonStats>();
        //Add season stats for each year
        this.SeasonStats.Add(2012, new SeasonStats());
        this.SeasonStats.Add(2011, new SeasonStats());
        this.SeasonStats.Add(2010, new SeasonStats());
    }
}

public class SeasonStats
{
    public int Goals { get; set; }
    public int Assists { get; set; }
}

我想使用 Entity Framework 来存储对象,但我不确定要在 SeasonStats 属性上放置哪些属性才能让 Entity 正确存储对象。

4

1 回答 1

1

由于 SeasonStats 是一个与 Player 严格相关的类,这意味着没有 Player 就不可能有 SeasonStats,因此您必须定义它们之间的组合关系。这意味着你必须声明一个一对多的关系,SeasonStats 正好在 Player 上,首先你必须像这样修改类

public class PlayerModel
{
    [Key]
    public int PlayerID { get; set; }
    [InverseProperty("Player")]
    public ICollection<SeasonStats> SeasonStats { get; set; }

    public PlayerModel()
    {
        this.SeasonStats = new List<SeasonStats>();
        //Add season stats for each year
        this.SeasonStats.Add(new SeasonStats(){Year = 2012};);
        this.SeasonStats.Add(new SeasonStats(){Year = 2011};);
        this.SeasonStats.Add(new SeasonStats(){Year = 2010};);
    }
}

public class SeasonStats
{
    [Key]
    public int Year { get; set;}
    public int Goals { get; set; }
    public int Assists { get; set; }
    [ForeignKey("PlayerID")]
    public Player Player{get; set; }
    [Required]
    public int PlayerID {get; set; }
}
于 2013-09-22T07:54:01.457 回答