Created
September 22, 2025 09:16
-
-
Save ljamel/e838da94ee91b77c935b63d22de35c4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.EntityFrameworkCore; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
var builder = WebApplication.CreateBuilder(args); | |
// ne pas oublier d'ajouter la dépendance nuget dotnet add package Microsoft.EntityFrameworkCore.InMemory | |
// et dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer | |
// Enregistrement du DbContext | |
builder.Services.AddDbContext<PersonContext>(opt => | |
opt.UseInMemoryDatabase("PeopleDb")); | |
var app = builder.Build(); | |
// Ajout de personnes au démarrage (données de test) | |
using (var scope = app.Services.CreateScope()) | |
{ | |
var db = scope.ServiceProvider.GetRequiredService<PersonContext>(); | |
// Ajoute des personnes seulement si la base est vide | |
if (!db.Person.Any()) | |
{ | |
db.Person.AddRange( | |
new Person { Name = "Alice" }, | |
new Person { Name = "Bob" }, | |
new Person { Name = "Charlie" } | |
); | |
db.SaveChanges(); | |
} | |
} | |
var group = app.MapGroup("/"); | |
group.MapGet("/", async (PersonContext db) => | |
{ | |
return await db.Person.ToListAsync(); | |
}); | |
group.MapGet("/{id}", async (int id, PersonContext db) => | |
{ | |
var person = await db.Person.FindAsync(id); | |
return person is not null ? Results.Ok(person) : Results.NotFound(); | |
}); | |
group.MapPost("/create", async (Person person, PersonContext db) => | |
{ | |
db.Person.Add(person); | |
await db.SaveChangesAsync(); | |
return Results.Created($"/people/{person.Id}", person); | |
}); | |
app.Run(); | |
// Classe Person | |
public class Person | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
// DbContext | |
public class PersonContext : DbContext | |
{ | |
public PersonContext(DbContextOptions<PersonContext> options) | |
: base(options) { } | |
public DbSet<Person> Person { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment