reciosonny
8/29/2017 - 3:04 PM

ApiMvcController.cs

[Route("/api/vehicles")]
public class VehiclesController : Controller {
    private readonly IMapper mapper;
    private readonly IVehicleRepository vehicleRepository;
    private readonly IUnitOfWork unitOfWork;
    public VehiclesController(IMapper mapper, IVehicleRepository vehicleRepository, IUnitOfWork unitOfWork)
    {
        this.vehicleRepository = vehicleRepository;
        this.mapper = mapper;
        this.unitOfWork = unitOfWork;
    }

    [HttpPost]
    [Authorize]
    public async Task<IActionResult> CreateVehicle([FromBody] SaveVehicleResource vehicleResource)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        // var model = await context.Models.FindAsync(vehicleResource.ModelId);
        // if (model == null)
        // {
        //     ModelState.AddModelError("ModelId", "Invalid Model ID");
        //     return BadRequest(ModelState);
        // }

        var vehicle = mapper.Map<SaveVehicleResource, Vehicle>(vehicleResource);
        vehicle.LastUpdate = DateTime.Now;

        vehicleRepository.Add(vehicle);
        await unitOfWork.CompleteAsync();

        vehicle = await vehicleRepository.GetVehicle(vehicle.Id);

        var result = mapper.Map<Vehicle, VehicleResource>(vehicle);

        return Ok(result);
    }
}