dotnet new webapi -minimal -o app01
Aktuális keretrendszerhez:
dotnet add package Microsoft.EntityFrameworkCore
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
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.MapControllers(); app.Run();
namespace App01.Controllers; [Route("api/[controller]")] [ApiController] public class EmployeeController : ControllerBase { [HttpGet] public string Get() { return "működik"; } }
create database sargabt; create table Employees( Id int not null primary key auto_increment, Name varchar(50), City varchar(50), Salary double );
public class Employee { public int Id { get; set; } public string? Name { get; set; } public string? City { get; set; } public double Salary { get; set; } }
{ "ConnectionStrings": { "Mariadb": "server=localhost;user=sargabt;password=titok;database=sargabt" } }
using Microsoft.EntityFrameworkCore; namespace App01.Data; public class DataService : DbContext { public DataService(DbContextOptions<DataService> options) :base(options) {} public DbSet<Employee> Employees {get; set;} = null!; }
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();
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; } }