Skip to content

Instantly share code, notes, and snippets.

@Atulin
Created June 10, 2025 19:34
Show Gist options
  • Select an option

  • Save Atulin/ecf28859efb5ed069871c3fde2c1f55e to your computer and use it in GitHub Desktop.

Select an option

Save Atulin/ecf28859efb5ed069871c3fde2c1f55e to your computer and use it in GitHub Desktop.
DTOs
// the database entity
public sealed class Person
{
public int Id { get; set; }
public string Name { get; set; }
public DateOnly Birthday { get; set; }
public int ShoeSize { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
[ApiController]
[Route("[controller")]
public sealed class PersonController(MyDbContext ctx) : ControllerBase
{
[HttpGet("{id:number}")]
public async Task<Results<NotFound, Ok<PersonDTO>>> GetPersonById(int id)
{
var person = await ctx.Persons
.Where(p => p.Id == id)
.Select(p => new PersonDTO(p.Name, p.Birthday, p.ShoeSize))
.FirstOrDefaultAsync();
return person is {} p ? TypedResults.Ok(p) : TypedResults.NotFound();
}
[HttpGet("deets/{id:number}")]
public async Task<Results<NotFound, Ok<PersonExtendedDTO>>> GetPersonDeetsById(int id)
{
var today = DateOnly.FromDateTime(DateTime.Today);
var person = await ctx.Persons
.Where(p => p.Id == id)
.Select(p => new PersonExtendedDTO {
Name = p.Name,
Age = today.Year - p.Birthday.Year,
ShoeSize = p.ShoeSize,
})
.FirstOrDefaultAsync();
return person is {} p ? TypedResults.Ok(p) : TypedResults.NotFound();
}
[HttpPut("{id:number}")] // We also use DTOs for receiving data
public async Task<Results<Ok, NotFound>> UpdateShoeSizeAndEmail(ShoeSizeAndEmail data)
{
var rows = await ctx.Persons.ExecuteUpdateAsync(s => s
.SetProperty(p => p.ShoeSize, data.ShoeSize)
.SetProperty(p => p.Email, data.Email)
);
return rows > 0 ? TypedResults.Ok() : TypedResults.NotFound();
}
public sealed record ShoeSizeAndEmail(int ShoeSize, string Email);
}
public sealed record PersonDTO(string Name, DateOnly Birthday, int ShoeSize);
// Could also be a class
public selaed class PersonExtendedDTO
{
public required string Name { get; init; }
public required int Age { get; init; }
public required int ShoeSize { get; init; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment