Created
August 7, 2020 09:16
-
-
Save corespider/447d17a8ad99c44894043cd50b7bfe35 to your computer and use it in GitHub Desktop.
ASP .NET Web API CRUD operation using Entity Framework-Controller
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
public class CustomersController : ApiController | |
{ | |
private CustomerAPIContext db = new CustomerAPIContext(); | |
// GET: api/Customers | |
public IQueryable<Customer> GetCustomers() | |
{ | |
return db.Customers; | |
} | |
// GET: api/Customers/5 | |
[ResponseType(typeof(Customer))] | |
public IHttpActionResult GetCustomer(int id) | |
{ | |
Customer customer = db.Customers.Find(id); | |
if (customer == null) | |
{ | |
return NotFound(); | |
} | |
return Ok(customer); | |
} | |
// PUT: api/Customers/5 | |
[ResponseType(typeof(void))] | |
public IHttpActionResult PutCustomer(int id, Customer customer) | |
{ | |
if (!ModelState.IsValid) | |
{ | |
return BadRequest(ModelState); | |
} | |
if (id != customer.CustId) | |
{ | |
return BadRequest(); | |
} | |
db.Entry(customer).State = EntityState.Modified; | |
try | |
{ | |
db.SaveChanges(); | |
} | |
catch (DbUpdateConcurrencyException) | |
{ | |
if (!CustomerExists(id)) | |
{ | |
return NotFound(); | |
} | |
else | |
{ | |
throw; | |
} | |
} | |
return StatusCode(HttpStatusCode.NoContent); | |
} | |
// POST: api/Customers | |
[ResponseType(typeof(Customer))] | |
public IHttpActionResult PostCustomer(Customer customer) | |
{ | |
if (!ModelState.IsValid) | |
{ | |
return BadRequest(ModelState); | |
} | |
db.Customers.Add(customer); | |
db.SaveChanges(); | |
return CreatedAtRoute("DefaultApi", new { id = customer.CustId }, customer); | |
} | |
// DELETE: api/Customers/5 | |
[ResponseType(typeof(Customer))] | |
public IHttpActionResult DeleteCustomer(int id) | |
{ | |
Customer customer = db.Customers.Find(id); | |
if (customer == null) | |
{ | |
return NotFound(); | |
} | |
db.Customers.Remove(customer); | |
db.SaveChanges(); | |
return Ok(customer); | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
if (disposing) | |
{ | |
db.Dispose(); | |
} | |
base.Dispose(disposing); | |
} | |
private bool CustomerExists(int id) | |
{ | |
return db.Customers.Count(e => e.CustId == id) > 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment