Add example function to project entity data into a DTO.

This commit is contained in:
Kevin Matsubara 2025-04-07 19:03:52 +02:00
parent fd6e601489
commit 9da28603c1

View File

@ -15,7 +15,24 @@ context.Database.EnsureCreated();
// Rather than raise: "System.InvalidOperationException: Sequence contains no elements." // Rather than raise: "System.InvalidOperationException: Sequence contains no elements."
// var firstCoach = await context.Coaches.FirstOrDefaultAsync(); // var firstCoach = await context.Coaches.FirstOrDefaultAsync();
await FilterScoredHomeMatches(); async Task ProjectionAndAnonymousDataTypes()
{
var teams = await context.Teams
.Select(t => new TeamDetailsDTO
{
TeamId = t.Id,
TeamName = t.Name,
CoachName = t.Coach.Name,
TotalHomeGoals = t.HomeMatches.Sum(m => m.HomeTeamScore),
TotalAwayGoals = t.AwayMatches.Sum(m => m.AwayTeamScore)
})
.ToListAsync();
foreach (var team in teams)
{
Console.WriteLine($"{team.TeamName} - {team.CoachName} | H: {team.TotalHomeGoals} | A: {team.TotalAwayGoals}");
}
}
async Task FilterScoredHomeMatches() async Task FilterScoredHomeMatches()
{ {
@ -429,3 +446,12 @@ class TeamInfoDTO
public DateTime Created { get; set; } public DateTime Created { get; set; }
public string Name { get; set; } public string Name { get; set; }
} }
class TeamDetailsDTO
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public string CoachName { get; set; }
public int TotalHomeGoals { get; set; }
public int TotalAwayGoals { get; set; }
}