I'm new to MVC and I am trying to work out how to connect different models to display in a view Example
Model Teams
int TeamID
string Team_Name
Model Players
int PlayerID
string PlayerName
Now I want this information stored in a database so how would I go about linking the two?
So in the Players Model I can use either Team Team or int TeamID
Team_ID
I can store in a db table but then have to somehow include the team table when I pull a list of players. or TEAM Team
which I can then view the team name by modelItem.team.team_name but cant store a TEAM object in the database.
I know this is basic in terms of MVC but im just struggling to get my head round it.
Any suggestions or links to solutions?
Your entity classes should look something like:
public class Team
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
public class Player
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Team")]
public int TeamId { get; set; }
public virtual Team Team { get; set; }
}
With that, with an instance of Player
, you can simply do:
player.Team.Name
To get the name of the team. If you have a collection of players you're iterating through, you should eagerly load Team
first, so you don't end up with N+1 queries:
var players = db.Players.Include(m => m.Team).ToList();
If you need to go the other way, then, you can load the list of players from an instance of Team
as well:
var players = team.Players.ToList();
Likewise, you can eagerly load the players to minimize queries:
var team = db.Teams.Include(m => m.Players).SingleOrDefault(m => m.Id == teamId);
For what it's worth, your class and property names defy conventions. Notice the class and property names in the sample code I provided. An entity class' name should always be singular: Team
, not Teams
. Property names should be pascal-cased and run together: LikeThis, not likeThis or Like_This. Also, it's an antipattern to include the class name in the property name. The Name
property belongs to Team
, for example, so of course it's the name of the team. There is zero point in prefixing it with Team
(TeamName
), and it only makes your code more verbose. For example, which reads better: team.Name
or team.TeamName
?