将List <object>添加到EF </object>

时间:2012-12-15 15:04:07

标签: c# entity-framework list

我正在玩EF,试图找到我的方向。现在我正在为一个网站写一个二十一点游戏。问题在于,无论何时从数据库中提取GameStateplayerHanddealerHandtheDeckdealerHidden属性都为空。

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; }
}

填充卡片和牌组表。我哪里错了?

1 个答案:

答案 0 :(得分:1)

我认为您需要通过制作虚拟属性来制作导航属性,即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