I'm new to ASP.NET, and am wondering how to create CRUD pages for a Model which has Lists of other Models ? I followed this tutorial, which creates CRUD pages for a simple scenario in which the Model has primitive data types only. So as such, the DbContext created is only for that one Model used in the tutorial. But what if I have two Models which have a One-to-Many relationship between them, such as the following scenario ?
public class Player
{
public string name {get; set;}
public int age {get; set;}
public double salary {get; set;}
public string gender {get; set;}
public DateTime contractSignDate {get; set;}
}
public class Team
{
public string teamName {get; set;}
public string sportPlayed {get; set;}
public List<Player> players {get; set;}
}
If I want to create CRUD pages for the Team Model, the DbContext I make for it refers to that Model only. In fact, VS2013's scaffolding engine doesn't even both with the players
List and simply ignores it outright.
How to solve this ?
This is the DbContext I made for the Team Model:
public class TeamDBContext : DbContext
{
public DbSet<Team> Teams { get; set; }
}
First, I would define the Player class as follows:
public class Player
{
//you need to define an identifier
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;}
public DateTime ContractSignDate {get; set;}
//you need a foreignkey
[ForeignKey("TeamId")]
public Team Team {get;set;}
public int TeamId {get;set;}
}
And Team class:
public class Team
{
//you need an identifier
public int TeamId {get;set;}
public string TeamName {get; set;}
public string SportPlayed {get; set;}
public List<Player> Players {get; set;}
}
And your dbcontext file:
public class TeamDBContext : DbContext
{
public DbSet<Team> Teams { get; set; }
public DbSet<Player> Players { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Player>()
.HasRequired(p => p.Team)
.WithMany(t => t.Players)
.HasForeignKey(p => p.TeamId)
}
}
And, here is how you would a new team and player:
TeamDBContext db = new TeamDBContext();
//create a new player
Player p = new Player() {Name="make", Age=10, Salary=10, Gender="m" };
db.Players.Add(p);
db.SaveChanges();
//create a new team
Team t = new Team () {TeamName="barcelona", SportType="soccer"};
db.Teams.Add(t);
db.SaveChanges();
//add a player to a team
db.Teams.Include("Players").Players.Add(p);
db.SaveChanges();