First you need to choose a database to work with. For C # there are several options, the Microsoft SQL Server is the most complete option for work with C #.
To persist your data, it is recommended to use an Object Relational Mapper (ORM) relational object mapper. There are also several options, the most complete being the Entity Framework , which creates and modifies the bank for you according to your code, does lazy and anticipated load of aggregate data, takes care of some validations and some more resources.
In the Entity Framework, its Player
looks like this:
public class Player
{
[Key]
public int PlayerId { get; set; }
public int? TeamId { get; set; } // O jogador pode ou não ter um time
public string Name { get; set; }
public virtual Team Team { get; set; }
}
And your Team
:
public class Team
{
[Key]
public int TeamId { get; set; }
public string Name { get; set; }
public virtual ICollection<Player> PlayersInThisTeam { get; set; }
}
Inserting a Team:
public SeuProjetoContext context = new SeuProjetoContext();
context.Teams.Add(new Team {
Name = "Time"
});
context.SaveChanges();
Inserting a player:
public SeuProjetoContext context = new SeuProjetoContext();
context.Players.Add(new Player {
Name = "Jogador"
});
context.SaveChanges();
Updating a player:
public SeuProjetoContext context = new SeuProjetoContext();
var player = context.Players.FirstOrDefault(p => p.Name == "Jogador");
if (player != null)
{
player.Name = "Fulano";
context.Entry(player).State = EntityState.Modified;
context.SaveChanges();
}
Deleting a player
public SeuProjetoContext context = new SeuProjetoContext();
var player = context.Players.FirstOrDefault(p => p.Name == "Jogador");
if (player != null)
{
context.Players.Remove(player);
context.SaveChanges();
}
Selecting all players:
public SeuProjetoContext context = new SeuProjetoContext();
var allPlayers = context.Players.ToList();
Associating a team with a player
public SeuProjetoContext context = new SeuProjetoContext();
var player = context.Players.FirstOrDefault(p => p.Name == "Fulano");
if (player != null)
{
var timeJogador = context.Teams.FirstOfDefault(t => t.Name == "Time");
if (timeJogador != null)
{
player.Time = timeJogador;
context.Entry(player).State = EntityState.Modified;
context.SaveChanges();
}
}
Selecting a team and all its players (preload)
public SeuProjetoContext context = new SeuProjetoContext();
var timeComJogadores = context.Teams
.Include(t => t.PlayersInThisTeam)
.FirstOrDefault(t => t.Name == "Time");
// timeJogadores.PlayersInThisTeam virá com os jogadores populados.
Selecting a team and all its players (lazy load)
public SeuProjetoContext context = new SeuProjetoContext();
var timeComJogadores = context.Teams
.FirstOrDefault(t => t.Name == "Time");
var jogadores = timeComJogadores.PlayersInThisTeam.ToList(); // Aqui forço uma segunda consulta apenas com os jogadores.