【问题标题】:Model containing a list of other model in Entity Framework包含实体框架中其他模型列表的模型
【发布时间】:2015-12-20 13:42:15
【问题描述】:

这个问题可能看起来微不足道,但过去几天我真的一直在为此烦恼。 我正在尝试使用实体框架创建一对多关系。 我有两个模型。第一个模型是团队:

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

某处肯定有错误(甚至可能在主程序本身),因为即使应用程序运行时一切似乎都正常,第二次运行应用程序时,我能够从数据库中检索除团队之外的所有内容球员名单(基本上是空的)。

我会很感激任何帮助,我真的很绝望。 提前非常感谢。

【问题讨论】:

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


    【解决方案1】:

    您必须创建复杂类型属性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;}
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2013-04-17
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多