包含实体框架中其他模型列表的模型

时间:2015-12-20 13:42:16

标签: c# entity-framework entity-framework-4 one-to-many

这个问题可能看起来微不足道,但在过去的几天里我一直在脱掉头发。 我正在尝试使用Entity Framework创建一对多关系。 我有两个型号。第一个模型是团队:

public class Team
{
   public int TeamId {get;set;}
   public string TeamName {get;set;}
   public string SportType {get;set;}
   public List<Player> Players {get;set;}
}

如您所见,我希望我的团队包含一系列玩家。我的播放器类定义如下:

public class Player
{
   public int PlayerId {get;set;}
   public string Name {get;set;}
   public int Age {get;set;}
   public double Salary {get;set;}
   public string Gender {get;set;}

   [ForeignKey("TeamId")]
   public Team Team {get;set;}
}

那是我的dbcontext类:

public class TeamDbContext : DbContext
{
   public DbSet<Team> Teams {get;set;}
   public DbSet<Player> Players {get;set;}

   protected override void OnModelCreating(DbModelCreator modelBuilder)
   {
       modelBuilder.Entity<Player>().HasRequired<Team>(p => p.Team).WithMany(t => t.Players).HasForeignKey(p => p.TeamId);
   }

   public TeamDbContext() : base("TeamDb")
   {
   }
}

这是我的主要内容:

static void Main(string[] args) 
{    
   TeamDbContext db = new TeamDbContext();

   // Create a new Player    
   Player Ben = new Player() {Name = "Ben", Age = 10};                
   db.Players.Add(Ben);   
   db.SaveChanges();

   // Create a new Team    
   Team LosVegasTeam = new Team() {TeamName = "LosVegas", SportType = "Soccer"};    
   LosVegasTeam.Players = new List<Player> {Ben};
   db.Teams.Add(LosVegasTeam);    
   db.SaveChanges(); 
}

某处肯定存在错误(甚至可能在主要本身),因为即使在应用程序运行时,一切似乎都有效,第二次运行应用程序时,我能够从数据库中检索所有内容,除了Team& #39; s球员名单(基本上是空的)。

我很感激任何帮助,我真的很无望。 非常感谢。

1 个答案:

答案 0 :(得分:2)

您必须制作复杂的类型属性virtual才能启用延迟加载

public class Team
{
   public int TeamId {get;set;}
   public string TeamName {get;set;}
   public string SportType {get;set;}
   public virtual List<Player> Players {get;set;}
}

public class Player
{
   public int PlayerId {get;set;}
   public string Name {get;set;}
   public int Age {get;set;}
   public double Salary {get;set;}
   public string Gender {get;set;}

   [ForeignKey("TeamId")]
   public virtual Team Team {get;set;}
}