我正在尝试使用EntityFramework Code-First将游戏保存在数据库中。

我的课程有一些片段:

/// <summary>
/// Game class
/// </summary>
public class Game : ObservableObject
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int GameId { get; set; }

    /// <summary>
    /// List of teams
    /// <see cref="Models.Teams"/>
    /// </summary>
    public Teams Teams
    {
        get
        {
            return teams;
        }
        set
        {
            teams = value;
            OnPropertyChanged("Teams");
        }
    }
}


/// <summary>
/// Teams class
/// </summary>
public class Teams : ObservableObject, IEnumerable<Team>
{
    public int GameId { get; set; }

    public Game Game { get; set;}

    List<Team> teamsList = new List<Team>();

    /// <summary>
    /// List of teams
    /// </summary>
    public List<Team> TeamsList
    {
        get
        {
            return teamsList;
        }
        set
        {
            teamsList = value;
            OnPropertyChanged("TeamsList");
        }
    }
}

/// <summary>
/// Team (group of players)
/// </summary>
public class Team : ObservableObject
{


    #region Properties & fields

    List<Player> players = null;
    static int NumberOfTeams = 0;

    /// <summary>
    /// List of players in team
    /// </summary>
    public List<Player> Players
    {
        get
        {
            return players;
        }
        set
        {
            players = value;

            OnPropertyChanged("NumberOfPlayers");
            OnPropertyChanged("IsEmpty");
            OnPropertyChanged("IsNotDefault");
            OnPropertyChanged("Players");
        }
    }
}

/// <summary>
///Defines player
/// </summary>
public class Player : Models.Person
{

    /// <summary>
    /// Identifies player in game. Also lets to recover player's statistics from last month
    /// </summary>
    public int PlayerId { get; set; }
}


而实体框架部分:

 public class GameContext : DbContext
{
    public GameContext() : base("Db")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = true;
    }

    public DbSet<Models.Game> Games { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure domain classes using modelBuilder here

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Models.Devices>().HasKey(d => d.GameId);
        modelBuilder.Entity<Models.Players>().HasKey(p => p.TeamId);
        modelBuilder.Entity<Models.Teams>().HasKey(t => t.GameId);
        modelBuilder.Entity<Models.Scenario>().HasKey(s => s.GameId);

        modelBuilder.Entity<Models.Game>().HasOptional<Models.Teams>(g => g.Teams).WithRequired(t => t.Game);
        modelBuilder.Entity<Models.Game>().HasOptional<Models.Scenario>(g => g.Scenario).WithRequired(s => s.Game);
        modelBuilder.Entity<Models.Game>().HasOptional<Models.Devices>(g => g.Devices).WithRequired(d => d.Game);

    }
}
 public static class GameService
{
    public static List<Models.Game> GetGames()
    {
        using (var gctx = new Contexts.GameContext())
        {
            return gctx.Games.ToList();
        }
    }

    public static void InsertGame(Models.Game game)
    {
        using (var gctx = new Contexts.GameContext())
        {
            gctx.Games.Add(game);
            gctx.SaveChanges();
        }
    }
}


我试图像这样使用它:

List<Models.Game> games = Services.GameService.GetGames().ToList();

        foreach(var game in games)
        {
            Console.WriteLine("Game " + game.GameId);

            foreach (var team in game.Teams)
            {
                Console.Write("\t");
                Console.WriteLine("Team" + team.Number);
                foreach(var player in team.Players)
                {
                    Console.Write("\t\t");
                    Console.WriteLine("Player" + player.PlayerId);
                }
            }
        }


当我运行此代码时,我会看到自己的游戏,该游戏的团队,但我无法联系到每个团队的玩家。所以我的问题是:我在这里做错了什么?

最佳答案

好,我解决了我的问题。造成该问题的原因很少。


需要使用Include进行急切加载。方法看起来像这样:

public static List<Models.Game> GetGames()
{
    using (var gctx = new Contexts.DatabaseContext())
    {

        return gctx.Games.Include(g => g.Teams).Include(g => g.Teams.TeamsList.Select(t => t.Players)).ToList();
    }
}

我使用Fluent API来确定关系(覆盖DatabaseContext.OnModelCreating):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Models.Game>().HasOptional(g => g.Teams).WithOptionalPrincipal(t => t.Game); // 1 -> 0..1
    modelBuilder.Entity<Models.Game>().HasOptional(g => g.Devices).WithOptionalPrincipal(d => d.Game); // 1 -> 0..1
    modelBuilder.Entity<Models.Game>().HasOptional(g => g.Scenario).WithOptionalPrincipal(s => s.Game); // 1-> 0..1

    modelBuilder.Entity<Models.Teams>().HasMany(ts => ts.TeamsList).WithRequired(t => t.Teams); // 1 -> many
    modelBuilder.Entity<Models.Team>().HasMany(t => t.Players).WithRequired(p => p.Team); // 1 -> many

    base.OnModelCreating(modelBuilder);


}

仅在Game类中,导航属性不是虚拟的。


感谢您在这种情况下的任何帮助。你们真棒!

关于c# - Entity Framework -未加载项目列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40173613/

10-17 00:03