-
Notifications
You must be signed in to change notification settings - Fork 279
/
Edit.cshtml.cs
106 lines (86 loc) · 2.86 KB
/
Edit.cshtml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using ContosoUniversity.Data;
using ContosoUniversity.Models;
using FluentValidation;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
namespace ContosoUniversity.Pages.Courses;
public class Edit : PageModel
{
private readonly IMediator _mediator;
[BindProperty]
public Command Data { get; set; }
public Edit(IMediator mediator) => _mediator = mediator;
public async Task OnGetAsync(Query query) => Data = await _mediator.Send(query);
public async Task<IActionResult> OnPostAsync()
{
await _mediator.Send(Data);
return this.RedirectToPageJson(nameof(Index));
}
public record Query : IRequest<Command>
{
public int? Id { get; init; }
}
public class QueryValidator : AbstractValidator<Query>
{
public QueryValidator()
{
RuleFor(m => m.Id).NotNull();
}
}
public class QueryHandler : IRequestHandler<Query, Command>
{
private readonly SchoolContext _db;
private readonly IConfigurationProvider _configuration;
public QueryHandler(SchoolContext db, IConfigurationProvider configuration)
{
_db = db;
_configuration = configuration;
}
public Task<Command> Handle(Query message, CancellationToken token) =>
_db.Courses
.Where(c => c.Id == message.Id)
.ProjectTo<Command>(_configuration)
.SingleOrDefaultAsync(token);
}
public record Command : IRequest
{
[Display(Name = "Number")]
public int Id { get; init; }
public string Title { get; init; }
public int? Credits { get; init; }
public Department Department { get; init; }
}
public class MappingProfile : Profile
{
public MappingProfile() => CreateProjection<Course, Command>();
}
public class CommandValidator : AbstractValidator<Command>
{
public CommandValidator()
{
RuleFor(m => m.Title).NotNull().Length(3, 50);
RuleFor(m => m.Credits).NotNull().InclusiveBetween(0, 5);
}
}
public class CommandHandler : IRequestHandler<Command, Unit>
{
private readonly SchoolContext _db;
public CommandHandler(SchoolContext db) => _db = db;
public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
var course = await _db.Courses.FindAsync(request.Id);
course.Title = request.Title;
course.Department = request.Department;
course.Credits = request.Credits!.Value;
return default;
}
}
}