Improve get Team by Id and include Coach and League.
Also add IgnoreCycles to options to prevent recursive problem.
This commit is contained in:
parent
30c3621deb
commit
cbcfb5536d
@ -45,7 +45,16 @@ namespace EntityFrameworkCore.API.Controllers
|
||||
[HttpGet("{id}")]
|
||||
public async Task<ActionResult<Team>> 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)
|
||||
{
|
||||
|
||||
@ -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
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user