Created
August 2, 2016 04:07
-
-
Save DamianEdwards/eb4f54eff9ef2464e67503b813d7c5d7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Threading.Tasks; | |
| using Microsoft.AspNetCore.Mvc; | |
| using WebApplication21.Data; | |
| using WebApplication21.Models; | |
| namespace WebApplication21.Controllers | |
| { | |
| [Route("api/[controller]")] | |
| public class ProductsController : ControllerBase | |
| { | |
| private readonly ProductsDbContext _db; | |
| public ProductsController(ProductsDbContext db) | |
| { | |
| _db = db; | |
| } | |
| [HttpGet("{id}")] | |
| public IActionResult Get(int id) | |
| { | |
| var product = _db.Products.SingleOrDefault(p => p.Id == id); | |
| if (product == null) | |
| { | |
| return NotFound(); | |
| } | |
| return Ok(product); | |
| } | |
| [HttpGet] | |
| public List<Product> GetAll() => _db.Products.ToList(); | |
| [HttpPost] | |
| public IActionResult Create([FromBody] Product product) | |
| { | |
| if (!ModelState.IsValid) | |
| { | |
| return BadRequest(ModelState); | |
| } | |
| _db.Add(product); | |
| _db.SaveChanges(); | |
| return CreatedAtAction(nameof(Get), new { id = product.Id }, product); | |
| } | |
| [HttpPut] | |
| public IActionResult Update([FromBody] Product product) | |
| { | |
| if (!ModelState.IsValid) | |
| { | |
| return BadRequest(ModelState); | |
| } | |
| _db.Update(product); | |
| _db.SaveChanges(); | |
| return NoContent(); | |
| } | |
| [HttpDelete("{id}")] | |
| public IActionResult Delete(int id) | |
| { | |
| var product = Get(id); | |
| if (product == null) | |
| { | |
| return NotFound(); | |
| } | |
| _db.Remove(product); | |
| _db.SaveChanges(); | |
| return NoContent(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment