Last active
March 16, 2022 07:53
-
-
Save LuisYordano/8e4a81f3e3f50c663bf96087f7b68b95 to your computer and use it in GitHub Desktop.
Minimal API CRUD .NET 6.0
This file contains 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; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddDbContext<RobotDbContext>(opt => opt.UseInMemoryDatabase("DBRobot")); | |
var app = builder.Build(); | |
if (app.Environment.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
app.MapGet("/", () => "Hello World!"); | |
app.MapGet("/robots", async (RobotDbContext db) => | |
{ | |
return await db.Robotics.ToListAsync(); | |
}); | |
app.MapGet("/robots/{id}", async (RobotDbContext db, int id) => | |
{ | |
return await db.Robotics.FindAsync(id) is Robot robot ? Results.Ok(robot) : Results.NotFound(); | |
}); | |
app.MapPost("/robots", async (RobotDbContext db, Robot robot) => | |
{ | |
await db.Robotics.AddAsync(robot); | |
await db.SaveChangesAsync(); | |
return Results.Ok(robot); | |
}); | |
app.MapPut("/robots/{id}", async (RobotDbContext db, int id, Robot inputRobot) => | |
{ | |
if (await db.Robotics.FindAsync(id) is Robot robot) | |
{ | |
robot.Company = inputRobot.Company; | |
robot.Name = inputRobot.Name; | |
await db.SaveChangesAsync(); | |
return Results.NoContent(); | |
} | |
else | |
{ | |
return Results.NotFound(); | |
} | |
}); | |
app.MapDelete("/robots/{id}", async (RobotDbContext db, int id) => | |
{ | |
if (await db.Robotics.FindAsync(id) is Robot robot) | |
{ | |
db.Robotics.Remove(robot); | |
await db.SaveChangesAsync(); | |
return Results.Ok(); | |
} | |
else | |
{ | |
return Results.NotFound(); | |
} | |
}); | |
app.Run(); | |
public class RobotDbContext : DbContext | |
{ | |
public RobotDbContext(DbContextOptions options) : base(options) { } | |
public DbSet<Robot> Robotics { get; set; } | |
} | |
public class Robot | |
{ | |
public int Id { get; set; } | |
public string Company { get; set; } | |
public string Name { get; set; } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment