From cbcfb5536d8e2edd1f7cedfb4443f99c75dc25db Mon Sep 17 00:00:00 2001 From: Kevin Matsubara Date: Mon, 14 Apr 2025 13:15:53 +0200 Subject: [PATCH] Improve get Team by Id and include Coach and League. Also add IgnoreCycles to options to prevent recursive problem. --- .../Controllers/TeamsController.cs | 11 ++++++++++- EntityFrameworkCore.API/Program.cs | 7 ++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/EntityFrameworkCore.API/Controllers/TeamsController.cs b/EntityFrameworkCore.API/Controllers/TeamsController.cs index 5040852..0401c0d 100644 --- a/EntityFrameworkCore.API/Controllers/TeamsController.cs +++ b/EntityFrameworkCore.API/Controllers/TeamsController.cs @@ -45,7 +45,16 @@ namespace EntityFrameworkCore.API.Controllers [HttpGet("{id}")] public async Task> GetTeam(int id) { - var team = await _context.Teams.FindAsync(id); + if (_context.Teams == null) + { + return NotFound(); + } + + // using λ for fun here. + var team = await _context.Teams + .Include(λ => λ.Coach) + .Include(λ => λ.League) + .FirstOrDefaultAsync(λ => λ.Id == id); if (team == null) { diff --git a/EntityFrameworkCore.API/Program.cs b/EntityFrameworkCore.API/Program.cs index c509de9..8cca952 100644 --- a/EntityFrameworkCore.API/Program.cs +++ b/EntityFrameworkCore.API/Program.cs @@ -1,11 +1,16 @@ using EntityFrameworkCore.Data; using Microsoft.EntityFrameworkCore; +using System.Text.Json.Serialization; using EntityFrameworkCore.API.Controllers; var builder = WebApplication.CreateBuilder(args); -builder.Services.AddControllers(); +builder.Services.AddControllers().AddJsonOptions(options => +{ + // IgnoreCycles prevents "System.Text.Json.JsonException: A possible object cycle was detected". + options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; +}); // Add services to the container. // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi