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 CatAPI.Data;
using CatAPI.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<ICatService, CatService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
namespace CatAPI.Models;
public class Cat
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Breed { get; set; } = string.Empty;
}
using Microsoft.EntityFrameworkCore;
using CatAPI.Models;
namespace CatAPI.Data;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Cat> Cats => Set<Cat>();
}
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=CatDB;Trusted_Connection=True;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
namespace CatAPI.Dtos;
public class CreateCatRequest
{
public string Name { get; set; } = string.Empty;
public string Breed { get; set; } = string.Empty;
}
namespace CatAPI.Dtos;
public class UpdateCatRequest
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Breed { get; set; } = string.Empty;
}
namespace CatAPI.Dtos;
public class CatResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Breed { get; set; } = string.Empty;
}
using CatAPI.Dtos;
namespace CatAPI.Services;
public interface ICatService
{
Task<List<CatResponse>> GetAllCatsAsync();
Task<CatResponse?> GetCatByIdAsync(int id);
Task<CatResponse> AddCatAsync(CreateCatRequest cat);
Task<bool> UpdateCatAsync(int id, UpdateCatRequest cat);
Task<bool> DeleteCatAsync(int id);
}
using Microsoft.EntityFrameworkCore;
using CatAPI.Data;
using CatAPI.Dtos;
using CatAPI.Models;
namespace CatAPI.Services;
public class CatService(AppDbContext context) : ICatService
{
public async Task<CatResponse> AddCatAsync(CreateCatRequest cat)
{
var newCat = new Cat
{
Name = cat.Name,
Breed = cat.Breed
};
context.Cats.Add(newCat);
await context.SaveChangesAsync();
return new CatResponse
{
Id = newCat.Id,
Name = newCat.Name,
Breed = newCat.Breed
};
}
public async Task<bool> DeleteCatAsync(int id)
{
var catToDelete = await context.Cats.FindAsync(id);
if (catToDelete is null)
return false;
context.Cats.Remove(catToDelete);
await context.SaveChangesAsync();
return true;
}
public async Task<List<CatResponse>> GetAllCatsAsync()
=> await context.Cats.Select(c => new CatResponse
{
Id = c.Id,
Name = c.Name,
Breed = c.Breed
}).ToListAsync();
public async Task<CatResponse?> GetCatByIdAsync(int id)
{
var result = await context.Cats
.Where(c => c.Id == id)
.Select(c => new CatResponse
{
Id = c.Id,
Name = c.Name,
Breed = c.Breed
})
.FirstOrDefaultAsync();
return result;
}
public async Task<bool> UpdateCatAsync(int id, UpdateCatRequest cat)
{
var existingCat = await context.Cats.FindAsync(id);
if (existingCat is null)
return false;
existingCat.Name = cat.Name;
existingCat.Breed = cat.Breed;
await context.SaveChangesAsync();
return true;
}
}
using Microsoft.AspNetCore.Mvc;
using CatAPI.Dtos;
using CatAPI.Services;
namespace CatAPI.Controllers;
[Route("api/[controller]")]
[ApiController]
public class CatsController(ICatService service) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<List<CatResponse>>> GetCats()
=> Ok(await service.GetAllCatsAsync());
[HttpGet("{id}")]
public async Task<ActionResult<CatResponse>> GetCat(int id)
{
var cat = await service.GetCatByIdAsync(id);
return cat is null ? NotFound("Gato com ID não encontrado") : Ok(cat);
}
[HttpPost]
public async Task<ActionResult<CatResponse>> AddCat(CreateCatRequest cat)
{
var createdCat = await service.AddCatAsync(cat);
return CreatedAtAction(nameof(GetCat), new { id = createdCat.Id }, createdCat);
}
[HttpPut("{id}")]
public async Task<ActionResult> UpdateCat(int id, UpdateCatRequest cat)
{
var updated = await service.UpdateCatAsync(id, cat);
return updated ? Ok() : NotFound("Gato com ID não encontrado");
}
[HttpDelete("{id}")]
public async Task<ActionResult> DeleteCat(int id)
{
var deleted = await service.DeleteCatAsync(id);
return deleted ? NoContent() : NotFound("Gato com ID não encontrado");
}
}
Em breve.
Elaborado por Mateus Schwede
ubsocial.github.io