Created
April 12, 2019 21:56
-
-
Save Rudyzio/0c9a0b57b29f86d2a5a309bdcc554bbf 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
[Route("api/[controller]")] | |
[ApiController] | |
public class UsersController : ControllerBase | |
{ | |
private readonly ApplicationDbContext _context; | |
public UsersController(ApplicationDbContext context) | |
{ | |
_context = context; | |
} | |
// GET: api/Users | |
[HttpGet] | |
public async Task<ActionResult<IEnumerable<User>>> GetUsers() | |
{ | |
return await _context.Users.Include(x => x.Recipes).ThenInclude(x => x.Ingredients).ToListAsync(); | |
} | |
// GET: api/Users/5 | |
[HttpGet("{id}")] | |
public async Task<ActionResult<User>> GetUser(int id) | |
{ | |
var user = await _context.Users.FindAsync(id); | |
if (user == null) | |
{ | |
return NotFound(); | |
} | |
return user; | |
} | |
// PUT: api/Users/5 | |
[HttpPut("{id}")] | |
public async Task<IActionResult> PutUser(int id, User user) | |
{ | |
if (id != user.Id) | |
{ | |
return BadRequest(); | |
} | |
_context.Entry(user).State = EntityState.Modified; | |
try { | |
await _context.SaveChangesAsync(); | |
} catch (DbUpdateConcurrencyException) | |
{ | |
if (!UserExists(id)) | |
{ | |
return NotFound(); | |
} | |
else | |
{ | |
throw; | |
} | |
} | |
return NoContent(); | |
} | |
// POST: api/Users | |
[HttpPost] | |
public async Task<ActionResult<User>> PostUser(User user) | |
{ | |
_context.Users.Add(user); | |
await _context.SaveChangesAsync(); | |
return CreatedAtAction("GetUser", new { id = user.Id }, user); | |
} | |
// DELETE: api/Users/5 | |
[HttpDelete("{id}")] | |
public async Task<ActionResult<User>> DeleteUser(int id) | |
{ | |
var user = await _context.Users.FindAsync(id); | |
if (user == null) | |
{ | |
return NotFound(); | |
} | |
_context.Users.Remove(user); | |
await _context.SaveChangesAsync(); | |
return user; | |
} | |
private bool UserExists(int id) | |
{ | |
return _context.Users.Any(e => e.Id == id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment