120 lines
3.4 KiB
C#
120 lines
3.4 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ScrumTaskboard.Controllers
|
|
{
|
|
[Route("[controller]")]
|
|
[ApiController]
|
|
public class UsersController : ControllerBase
|
|
{
|
|
private readonly TaskContext _context;
|
|
|
|
public UsersController(TaskContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
// GET: api/sprint
|
|
#nullable enable
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<ScrumUser>>> GetUser([FromQuery]string? name)
|
|
{
|
|
var filtered = _context.Users.AsQueryable();
|
|
if (name != null)
|
|
{
|
|
filtered = filtered.Where<ScrumUser>(u => u.name.Contains(name));
|
|
}
|
|
|
|
return await filtered.ToListAsync();
|
|
}
|
|
#nullable disable
|
|
|
|
// GET: api/sprint/5
|
|
[HttpGet("{id}")]
|
|
public async Task<ActionResult<ScrumUser>> GetUser(int id)
|
|
{
|
|
var User = await _context.Users.FindAsync(id);
|
|
|
|
if (User == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
return User;
|
|
}
|
|
|
|
// PUT: api/sprint/5
|
|
[HttpPut("{id}")]
|
|
public async Task<IActionResult> PutUser(int id, ScrumUser sprint)
|
|
{
|
|
// Die ID des Users darf nicht geändert werden
|
|
if (id != sprint.id)
|
|
{
|
|
return BadRequest();
|
|
}
|
|
|
|
// Speichere den geänderten User im Context
|
|
_context.Entry(sprint).State = EntityState.Modified;
|
|
|
|
try
|
|
{
|
|
// Übernehme die Änderungen in die Datenbank
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
catch (DbUpdateConcurrencyException)
|
|
{
|
|
// Wenn der User nicht existiert, gib Statuscode 404 zurück
|
|
if (!UserExists(id))
|
|
{
|
|
return NotFound();
|
|
}
|
|
else
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
|
|
return NoContent();
|
|
}
|
|
|
|
// POST: api/User
|
|
[HttpPost]
|
|
public async Task<ActionResult<ScrumUser>> PostUser(ScrumUser sprint)
|
|
{
|
|
_context.Users.Add(sprint);
|
|
await _context.SaveChangesAsync();
|
|
|
|
// Der neue User wurde erstellt und kann über die GetUser Methode abgerufen werden.
|
|
return CreatedAtAction("GetUser", new { id = sprint.id }, sprint);
|
|
}
|
|
|
|
// DELETE: api/User/5
|
|
[HttpDelete("{id}")]
|
|
public async Task<ActionResult<ScrumUser>> DeleteUser(int id)
|
|
{
|
|
var scrumUser = await _context.Users.FindAsync(id);
|
|
if (scrumUser == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
// Entferne den User aus dem Context
|
|
_context.Users.Remove(scrumUser);
|
|
// Speichere die Änderungen in der Datenbank
|
|
await _context.SaveChangesAsync();
|
|
|
|
return scrumUser;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Prüft, ob ein User mit der angegebenen ID bereits existiert.
|
|
/// </summary>
|
|
private bool UserExists(int id)
|
|
{
|
|
return _context.Users.Any(e => e.id == id);
|
|
}
|
|
}
|
|
} |