srumboard_backend/ScrumTaskboard/Controllers/ProjectsController.cs

126 lines
3.8 KiB
C#

using System;
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 ProjectsController : ControllerBase
{
private readonly TaskContext _context;
public ProjectsController(TaskContext context)
{
_context = context;
}
// GET: api/projects
#nullable enable
[HttpGet]
public async Task<ActionResult<IEnumerable<ScrumProject>>> GetProject([FromQuery]string? title, [FromQuery]bool? isprivate)
{
var filtered = _context.Projects.AsQueryable();
if (title != null)
{
filtered = filtered.Where<ScrumProject>(t => t.Title.Contains(title));
}
if (isprivate != null)
{
filtered = filtered.Where<ScrumProject>(t => t.IsPrivate == isprivate);
}
return await filtered.ToListAsync();
}
#nullable disable
// GET: api/projects/5
[HttpGet("{id}")]
public async Task<ActionResult<ScrumProject>> GetProjects(int id)
{
var project = await _context.Projects.FindAsync(id);
if (project == null)
{
return NotFound();
}
return project;
}
// PUT: api/Project/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProject(int id, ScrumProject projects)
{
// Die ID des Projects darf nicht geändert werden
if (id != projects.Id)
{
return BadRequest();
}
// Speichere den geänderten Project im Context
_context.Entry(projects).State = EntityState.Modified;
try
{
// Übernehme die Änderungen in die Datenbank
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
// Wenn der Project nicht existiert, gib Statuscode 404 zurück
if (!ProjectExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Project
[HttpPost]
public async Task<ActionResult<ScrumProject>> PostProject(ScrumProject projects)
{
_context.Projects.Add(projects);
await _context.SaveChangesAsync();
// Der neue Project wurde erstellt und kann über die GetProject Methode abgerufen werden.
return CreatedAtAction("GetProject", new { id = projects.Id }, projects);
}
// DELETE: api/Project/5
[HttpDelete("{id}")]
public async Task<ActionResult<ScrumProject>> DeleteProject(int id)
{
var scrumProject = await _context.Projects.FindAsync(id);
if (scrumProject == null)
{
return NotFound();
}
// Entferne den Project aus dem Context
_context.Projects.Remove(scrumProject);
// Speichere die Änderungen in der Datenbank
await _context.SaveChangesAsync();
return scrumProject;
}
/// <summary>
/// Prüft, ob ein Project mit der angegebenen ID bereits existiert.
/// </summary>
private bool ProjectExists(int id)
{
return _context.Projects.Any(e => e.Id == id);
}
}
}