JPHD-2021-backend/Pages/Students/Delete.cshtml.cs

68 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using _2021_backend.Data;
using _2021_backend.Models;
namespace _2021_backend.Pages.Students
{
public class DeleteModel : PageModel
{
private readonly _2021_backend.Data.BackendContext Context;
public DeleteModel(_2021_backend.Data.BackendContext context)
{
Context = context;
}
[BindProperty]
public Student Student { get; set; }
public async Task<IActionResult> OnGetAsync(string? idstr)
{
if (idstr == null)
{
return NotFound();
}
Guid id = Guid.Parse(idstr);
Student = await Context.Students.FirstOrDefaultAsync(m => m.Guid == id);
if (Student == null)
{
return NotFound();
}
return Page();
}
public async Task<IActionResult> OnPostAsync(string? idstr)
{
if (idstr == null)
{
return NotFound();
}
Guid id = Guid.Parse(idstr);
Student = await Context.Students.FindAsync(id);
if (Student != null)
{
var q = from e in Context.Sessions where e.Students.Contains(id) select e;
var lst = q.ToList();
foreach(var it in lst)
{
it.Students.RemoveAll(k => k == id);
}
Context.Students.Remove(Student);
Context.SaveChanges();
}
return RedirectToPage("./Index");
}
}
}