Basic Crud Operation In WebApi With CodeFirst
Here we create a Crud Application in WebApi with Entityframework CodeFirst and will use Scaffolding for generate code for crud operation.
Step 1:- Create a Project
Step 2:- Create a Model Class with name Student in model folder in your solution directory.
Step 4:- Connect the application to database using Connection String.
Step 5:- Add Controller class with option Controller with action using entity framework it will
generate crud method using scaffolding.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using crudin_api_withcodefirst.Models;
namespace crudin_api_withcodefirst.Controllers
{
public class StudentController : ApiController
{
private AppContext db = new AppContext();
//
GET: api/Student
public IQueryable<Student> GetStudent()
{
return db.Student;
}
//
GET: api/Student/5
[ResponseType(typeof(Student))]
public IHttpActionResult GetStudent(int id)
{
Student student = db.Student.Find(id);
if (student == null)
{
return NotFound();
}
return Ok(student);
}
//
PUT: api/Student/5
[ResponseType(typeof(void))]
public IHttpActionResult PutStudent(int id, Student student)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != student.Id)
{
return BadRequest();
}
db.Entry(student).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!StudentExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
//
POST: api/Student
[ResponseType(typeof(Student))]
public IHttpActionResult PostStudent(Student student)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Student.Add(student);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = student.Id },
student);
}
//
DELETE: api/Student/5
[ResponseType(typeof(Student))]
public IHttpActionResult DeleteStudent(int id)
{
Student student = db.Student.Find(id);
if (student == null)
{
return NotFound();
}
db.Student.Remove(student);
db.SaveChanges();
return Ok(student);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool StudentExists(int id)
{
return db.Student.Count(e => e.Id == id) > 0;
}
}
}
No comments:
Post a Comment