Last active
September 26, 2016 09:11
-
-
Save AndyButland/11de945d5b3824be043082402d5de189 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ComponentModel.DataAnnotations; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using AutoMapper; | |
using MediatR; | |
using Microsoft.AspNetCore.Mvc.Rendering; | |
using Microsoft.EntityFrameworkCore; | |
public class TasksEditViewModel | |
{ | |
public int Id { get; set; } | |
public bool IsAdding => Id == 0; | |
[Required(ErrorMessage = "Please provide a description")] | |
[StringLength(500, ErrorMessage = "The description cannot be | |
longer than 500 characters")] | |
public string Description { get; set; } | |
[Required] | |
[Display(Name = "Category")] | |
public int CategoryId { get; set; } | |
public SelectList CategoryOptions { get; set; } | |
} | |
public class TasksEditViewModelQuery : | |
IAsyncRequest<TasksEditViewModel> | |
{ | |
public int Id { get; set; } | |
} | |
public class TasksEditViewModelQueryHandler : | |
QueryHandlerBase, | |
IAsyncRequestHandler<TasksEditViewModelQuery,TasksEditViewModel> | |
{ | |
public TasksEditViewModelQueryHandler(ToDoContext context, | |
IMapper mapper) | |
: base(context, mapper) | |
{ | |
} | |
public async Task<TasksEditViewModel> Handle( | |
TasksEditViewModelQuery query) | |
{ | |
var model = new TasksEditViewModel(); | |
if (query.Id > 0) | |
{ | |
var task = await GetTask(query.Id); | |
Mapper.Map(task, model); | |
} | |
model.CategoryOptions = new SelectList( | |
await Context.Categories | |
.OrderBy(x => x.Name) | |
.ToListAsync(), "Id", "Name", model.CategoryId); | |
return model; | |
} | |
private async Task<Models.Task> GetTask(int id) | |
{ | |
var task = await Context.Tasks | |
.SingleOrDefaultAsync(x => x.Id == id); | |
if (task == null) | |
{ | |
throw new NullReferenceException($"Task with id: {id} not found."); | |
} | |
return task; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment