Tartalomjegyzék

< .Web API

REST API kontroller használat

Projekt készítése

dotnet new webapi -minimal -o app01

Függőségek telepítése

Aktuális

Aktuális keretrendszerhez:

dotnet add package Microsoft.EntityFrameworkCore

7-s verzióhoz

Keressük meg az utolsó 7.x verziót:

Ha kattintunk a verzióra, akkor kiírja hogyan kell telepíteni:

dotnet add package Microsoft.EntityFrameworkCore --version 7.0.15
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 7.0.0

Program.cs

Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
 
var app = builder.Build();
app.MapControllers();
app.Run();

Kontroller

EmployeeController.cs
namespace App01.Controllers;
 
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase {
    [HttpGet]
    public string Get() {
        return "működik";
    }
}

Adatbázis

create.sql
create database sargabt;
 
create table Employees(
    Id int not null primary key auto_increment,
    Name varchar(50),
    City varchar(50),
    Salary double
);

Modell

Employee.cs
public class Employee {
    public int Id { get; set; }
    public string? Name { get; set; }
    public string? City { get; set; }
    public double Salary { get; set; }
}

Adatbázis elérése

appsettings.Development.json
{
  "ConnectionStrings": {
    "Mariadb": "server=localhost;user=sargabt;password=titok;database=sargabt"
  }
}
DataService.cs
using Microsoft.EntityFrameworkCore;
 
namespace App01.Data;
 
public class DataService : DbContext {
    public DataService(DbContextOptions<DataService> options)
        :base(options) {}
 
    public DbSet<Employee> Employees {get; set;} = null!;
}
Program.cs
using Microsoft.EntityFrameworkCore;
using App01.Data;
 
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
 
builder.Services.AddDbContext<DataService>(options => {
    var connectionString = builder.Configuration.GetConnectionString("Mariadb");
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
 
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.MapControllers();
app.Run();

Kontroller

EmployeeController.cs
using App01.Data;
// using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
// using Microsoft.EntityFrameworkCore;
 
namespace App01.Controllers;
 
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase {
 
    private readonly DataService _db;
 
    public EmployeeController(DataService db) {
        _db = db;
    }
 
    [HttpGet]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]    
    public ActionResult<List<Employee>> Get() {
        var emps = _db.Employees.ToList();
        return emps == null ? NotFound() : emps;
    }
}