Loading [MathJax]/jax/output/HTML-CSS/jax.js

Wednesday, August 21, 2019

Standard CRUD in .NET

Just a record:
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
using ReallyTrue.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
 
namespace ReallyTrue
{
    public class CustomersController : ApiController
    {
        private ApplicationDbContext _context;
 
        public CustomersController()
        {
            _context = new ApplicationDbContext();
        }
 
        public IEnumerable<Customer> GetCustomers()
        {
            var customer = _context.Customers.SingleOrDefault(c => c.Id = id);
        }
 
        public Customer GetCustomer(int id)
        {
            var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
            if (customer == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return customer;
        }
 
        [HttpPost]
        public Customer CreateCustomer(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
 
            _context.Customers.Add(customer);
            _context.SaveChanges();
 
            return customer;
        }
 
        [HttpPut]
        public void UpdateCustomer(int id, Customer customer)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
 
            var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
 
            if (customerInDb == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
 
 
            customerInDb.Name = customer.Name;
            customerInDb.Birthday = customer.Birthday;
            customerInDb.IsSubscribedToNewsletter = customer.IsSubscribedToNewsletter;
            customerInDb.MembershipType = customer.MembershipType;
 
            _context.SaveChanges();
        }
 
        [HttpDelete]
        public void DeleteCustomer(int id)
        {
 
            var customerInDb = _context.Customers.SingleOrDefault(c => c.Id == id);
 
            if (customerInDb == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);
 
            _context.Customers.Remove(customerInDb);
            _context.SaveChanges();
        }
    }
}
Improvement of the code: We can replace ActionResult by IHttpActionResult, then
1
throw new HttpResponseException(HttpStatusCode.BadRequest)
can be replaced by
1
return BadRequest()
etc.

No comments:

Post a Comment