Reading from database ok even dto implemented

This commit is contained in:
2026-02-07 16:08:55 +01:00
parent 4a5fb36b8e
commit 585cac9d9c
9 changed files with 199 additions and 23 deletions

View File

@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using VideoGameCharacterApi.Dtos;
using VideoGameCharacterApi.Models; using VideoGameCharacterApi.Models;
using VideoGameCharacterApi.Services; using VideoGameCharacterApi.Services;
@ -11,11 +12,11 @@ namespace VideoGameCharacterApi.Controllers
{ {
[HttpGet] [HttpGet]
public async Task<ActionResult<List<Character>>> GetCharacters() public async Task<ActionResult<List<CharacterResponse>>> GetCharacters()
=> Ok(await service.GetCharactersAsync()); => Ok(await service.GetCharactersAsync());
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult<Character>> GetCharacter(int id) public async Task<ActionResult<CharacterResponse>> GetCharacter(int id)
{ {
var character = await service.GetCharacterByIdAsync(id); var character = await service.GetCharacterByIdAsync(id);
return character is null ? NotFound("Character with given id was not found") : Ok(character); return character is null ? NotFound("Character with given id was not found") : Ok(character);

View File

@ -0,0 +1,10 @@
namespace VideoGameCharacterApi.Dtos
{
public class CharacterResponse
{
//public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Game { get; set; } = string.Empty;
public string Role { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,54 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using VideoGameCharacterApi.Data;
#nullable disable
namespace VideoGameCharacterApi.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20260207133430_initial")]
partial class initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("VideoGameCharacterApi.Models.Character", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Game")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Characters");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace VideoGameCharacterApi.Migrations
{
/// <inheritdoc />
public partial class initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Characters",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Game = table.Column<string>(type: "nvarchar(max)", nullable: false),
Role = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Characters", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Characters");
}
}
}

View File

@ -0,0 +1,51 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using VideoGameCharacterApi.Data;
#nullable disable
namespace VideoGameCharacterApi.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("VideoGameCharacterApi.Models.Character", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Game")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Characters");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Scalar.AspNetCore; using Scalar.AspNetCore;
using VideoGameCharacterApi.Data;
using VideoGameCharacterApi.Services; using VideoGameCharacterApi.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -9,7 +11,7 @@ builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi(); builder.Services.AddOpenApi();
builder.services.AddDbContext<ApplicationDbContext>(options => builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IVideoGameCharacterService, VideoGameCharacterService>(); builder.Services.AddScoped<IVideoGameCharacterService, VideoGameCharacterService>();

View File

@ -1,12 +1,13 @@
using VideoGameCharacterApi.Models; using VideoGameCharacterApi.Dtos;
using VideoGameCharacterApi.Models;
namespace VideoGameCharacterApi.Services; namespace VideoGameCharacterApi.Services;
public interface IVideoGameCharacterService public interface IVideoGameCharacterService
{ {
Task<List<Character>> GetCharactersAsync(); Task<List<CharacterResponse>> GetCharactersAsync();
Task<Character> GetCharacterByIdAsync(int id); Task<CharacterResponse> GetCharacterByIdAsync(int id);
Task<Character> AddCharacterAsync(Character character); Task<CharacterResponse> AddCharacterAsync(Character character);
Task<Character> UpdateCharacterAsync(int id,Character character); Task<Character> UpdateCharacterAsync(int id,Character character);
Task<bool> DeleteCharacterAsync(int id); Task<bool> DeleteCharacterAsync(int id);
} }

View File

@ -1,19 +1,21 @@
using VideoGameCharacterApi.Models; using Microsoft.EntityFrameworkCore;
using VideoGameCharacterApi.Data;
using VideoGameCharacterApi.Dtos;
using VideoGameCharacterApi.Models;
namespace VideoGameCharacterApi.Services namespace VideoGameCharacterApi.Services
{ {
public class VideoGameCharacterService : IVideoGameCharacterService public class VideoGameCharacterService : IVideoGameCharacterService
{ {
static List<Character> characters = new List<Character> private readonly ApplicationDbContext _context;
public VideoGameCharacterService(ApplicationDbContext context)
{ {
new Character { Id = 1, Name = "Mario", Game = "Super Mario Bros.", Role = "hero" }, _context = context;
new Character { Id = 2, Name = "Link", Game = "The Legend of Zelda", Role = "hero" }, }
new Character { Id = 3, Name = "Bowser", Game = "Super Mario Bros.", Role = "villain" },
new Character { Id = 4, Name = "Zelda", Game = "The Legend of Zelda", Role = "princess" },
};
public Task<Character> AddCharacterAsync(Character character) public Task<CharacterResponse> AddCharacterAsync(Character character)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@ -23,15 +25,35 @@ namespace VideoGameCharacterApi.Services
throw new NotImplementedException(); throw new NotImplementedException();
} }
public async Task<Character> GetCharacterByIdAsync(int id) public async Task<CharacterResponse> GetCharacterByIdAsync(int id)
=> await Task.FromResult(characters.FirstOrDefault(c => c.Id == id)); {
var result = await _context.Characters
.Where(c => c.Id == id)
.Select(c => new CharacterResponse
{
Name = c.Name,
Game = c.Game,
Role = c.Role
})
.FirstOrDefaultAsync();
return result;
}
public async Task<List<Character>> GetCharactersAsync() public async Task<List<CharacterResponse>> GetCharactersAsync()
=> await Task.FromResult(characters); => await _context.Characters.Select(c => new CharacterResponse
{
Name = c.Name,
Game = c.Game,
Role = c.Role
}).ToListAsync();
public Task<Character> UpdateCharacterAsync(int id, Character character) public Task<Character> UpdateCharacterAsync(int id, Character character)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} };
} }

View File

@ -1,7 +1,6 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "" "DefaultConnection": "Server=TFOACERLAP;Database=VideoGameCharactersDB;Trusted_Connection=True;Encrypt=no;MultipleActiveResultSets=true"
"Server=TFOACERLAP;Database=VideoGameCharactersDB;Trusted_Connection=True;Encrypt=no;MultipleActiveResultSets=true\"\"",
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {