Framework web C#, que usa .NET Core. EF Core (Entity Framework Core) é ORM (Object-Relational Mapping) para .NET, instalado via 'dotnet tool install --global dotnet-ef'.
Utiliza-se Visual Studio, criar API web ASP .NET Core, configurações padrão. Projeto 1 do GitHub (acesse).
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore;
using VideoGameCharacterApi.Data;
using VideoGameCharacterApi.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IVideoGameCharacterService, VideoGameCharacterService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
namespace VideoGameCharacterApi.Models;
public class Character
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Game { get; set; } = string.Empty;
public string Role { get; set; } = string.Empty;
}
using Microsoft.AspNetCore.Mvc;
using VideoGameCharacterApi.Dtos;
using VideoGameCharacterApi.Services;
namespace VideoGameCharacterApi.Controllers;
[Route("api/[controller]")]
[ApiController]
public class VideoGameCharactersController(IVideoGameCharacterService service) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<List<CharacterResponse>>> GetCharacters()
=> Ok(await service.GetAllCharactersAsync());
[HttpGet("{id}")]
public async Task<ActionResult<CharacterResponse>> GetCharacter(int id)
{
var character = await service.GetCharacterByIdAsync(id);
return character is null ? NotFound("Character with the given Id was not found.") : Ok(character);
}
[HttpPost]
public async Task<ActionResult<CharacterResponse>> AddCharacter(CreateCharacterRequest character)
{
var createdCharacter = await service.AddCharacterAsync(character);
return CreatedAtAction(nameof(GetCharacter), new { id = createdCharacter.Id }, createdCharacter);
}
[HttpPut("{id}")]
public async Task<ActionResult> UpdateCharacter(int id, UpdateCharacterRequest character)
{
var updated = await service.UpdateCharacterAsync(id, character);
return updated ? Ok() : NotFound("Character with the given Id was not found.");
}
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteCharacter(int id)
{
var deleted = await service.DeleteCharacterAsync(id);
return deleted ? NoContent() : NotFound("Character with the given Id was not found.");
}
}
using VideoGameCharacterApi.Dtos;
namespace VideoGameCharacterApi.Services;
public interface IVideoGameCharacterService
{
Task<List<CharacterResponse>> GetAllCharactersAsync();
Task<CharacterResponse?> GetCharacterByIdAsync(int id);
Task<CharacterResponse> AddCharacterAsync(CreateCharacterRequest character);
Task<bool> UpdateCharacterAsync(int id, UpdateCharacterRequest character);
Task<bool> DeleteCharacterAsync(int id);
}
using Microsoft.EntityFrameworkCore;
using VideoGameCharacterApi.Data;
using VideoGameCharacterApi.Dtos;
using VideoGameCharacterApi.Models;
namespace VideoGameCharacterApi.Services;
public class VideoGameCharacterService(AppDbContext context) : IVideoGameCharacterService
{
public async Task<CharacterResponse> AddCharacterAsync(CreateCharacterRequest character)
{
var newCharacter = new Character
{
Name = character.Name,
Game = character.Game,
Role = character.Role
};
context.Characters.Add(newCharacter);
await context.SaveChangesAsync();
return new CharacterResponse
{
Id = newCharacter.Id,
Name = newCharacter.Name,
Game = newCharacter.Game,
Role = newCharacter.Role
};
}
public async Task<bool> DeleteCharacterAsync(int id)
{
var characterToDelete = await context.Characters.FindAsync(id);
if (characterToDelete is null)
return false;
context.Characters.Remove(characterToDelete);
await context.SaveChangesAsync();
return true;
}
public async Task<List<CharacterResponse>> GetAllCharactersAsync()
=> await context.Characters.Select(c => new CharacterResponse
{
Id = c.Id,
Name = c.Name,
Game = c.Game,
Role = c.Role
}).ToListAsync();
public async Task<CharacterResponse?> GetCharacterByIdAsync(int id)
{
var result = await context.Characters
.Where(c => c.Id == id)
.Select(c => new CharacterResponse
{
Id = c.Id,
Name = c.Name,
Game = c.Game,
Role = c.Role
})
.FirstOrDefaultAsync();
return result;
}
public async Task<bool> UpdateCharacterAsync(int id, UpdateCharacterRequest character)
{
var existingCharacter = await context.Characters.FindAsync(id);
if (existingCharacter is null)
return false;
existingCharacter.Name = character.Name;
existingCharacter.Game = character.Game;
existingCharacter.Role = character.Role;
await context.SaveChangesAsync();
return true;
}
}
using Microsoft.EntityFrameworkCore;
using VideoGameCharacterApi.Models;
namespace VideoGameCharacterApi.Data;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Character> Characters => Set<Character>();
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=VideoGameCharacterDb;Trusted_Connection=True;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
namespace VideoGameCharacterApi.Dtos;
public class CreateCharacterRequest
{
public string Name { get; set; } = string.Empty;
public string Game { get; set; } = string.Empty;
public string Role { get; set; } = string.Empty;
}
namespace VideoGameCharacterApi.Dtos;
public class UpdateCharacterRequest
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Game { get; set; } = string.Empty;
public string Role { get; set; } = string.Empty;
}
namespace VideoGameCharacterApi.Dtos;
public class CharacterResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Game { get; set; } = string.Empty;
public string Role { get; set; } = string.Empty;
}
Em breve.
Elaborado por Mateus Schwede
ubsocial.github.io