我正在和EF一起玩,试图了解我的方向。现在,我正在为网站编写二十一点游戏。问题是,每当我从数据库中提取GameState时,playerHanddealerHandtheDeckdealerHidden属性都为空。

public class GameState
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int gameSession { get; set; }
    public int playerScore { get; set; }
    public int dealerScore { get; set; }
    public Deck theDeck { get; set; }
    public List<Cards> playerHand { get; set; }
    public List<Cards> dealerHand { get; set; }
    public Cards dealerHidden { get; set; }
    public bool gameOver { get; set; }
}

public class Cards
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int cardId { get; set; }
    public string cardName { get; set; }
    public int cardValue { get; set; }
}

public class GameStateContext : DbContext
{
    public GameStateContext() : base("MyContext")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<GameState>().HasRequired(e => e.theDeck);
        modelBuilder.Entity<GameState>().HasRequired(e => e.dealerHand).WithMany().WillCascadeOnDelete(false);
        modelBuilder.Entity<GameState>().HasRequired(e => e.playerHand).WithMany().WillCascadeOnDelete(false);
        modelBuilder.Entity<GameState>().HasOptional(e => e.dealerHidden);
        modelBuilder.Entity<Deck>().HasRequired(e => e.cards).WithMany().WillCascadeOnDelete(false);
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<GameState> GameStates { get; set; }
    public DbSet<Deck> Decks { get; set; }
    public DbSet<Card> Cards { get; set; }
}


卡片和卡组表已填充。我要去哪里错了?

最佳答案

我认为您或者需要通过使其成为虚拟属性来使它们的导航属性(即playerHand,dealerHand,theDeck和DealerHidden可以延迟加载),或者在查询GameState时急切地加载它们。

myDBContext.GameStates.Include("playerHand").Include("dealerHand").Include("theDeck").Include("dealerHidden").where(...);


这是有关实体框架如何处理相关对象的恰当解释:

http://msdn.microsoft.com/en-us/data/jj574232.aspx

10-04 20:27