From 9da28603c190cefbcd24e66ad7ae5f6a2e6b1759 Mon Sep 17 00:00:00 2001 From: Kevin Matsubara Date: Mon, 7 Apr 2025 19:03:52 +0200 Subject: [PATCH] Add example function to project entity data into a DTO. --- EntityFrameworkCore.Console/Program.cs | 28 +++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/EntityFrameworkCore.Console/Program.cs b/EntityFrameworkCore.Console/Program.cs index 63590a4..7120de4 100644 --- a/EntityFrameworkCore.Console/Program.cs +++ b/EntityFrameworkCore.Console/Program.cs @@ -15,7 +15,24 @@ context.Database.EnsureCreated(); // Rather than raise: "System.InvalidOperationException: Sequence contains no elements." // 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() { @@ -428,4 +445,13 @@ class TeamInfoDTO { public DateTime Created { 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; } } \ No newline at end of file