using DbFirstApproach.Models;
using System;
using System.Diagnostics;
using System.Linq;
using System.Web.Http;
namespace DbFirstApproach.Controllers
{
public class AddStudentController : ApiController
{
[Route("api/addstudent")]
[HttpPost]
public string POST([FromBody]AddStudentModel studentInfo)
{
// get the largest id from db
var db = new StudentEntities();
var maxId = 0;
try
{
maxId = db.Students.Max(item => item.Id);
}
catch (Exception) { }
Student newStudent = new Student();
newStudent.Course = studentInfo.course;
newStudent.Name = studentInfo.name;
newStudent.RollNumber = studentInfo.rollNumber;
newStudent.Id = ++maxId;
db.Students.Add(newStudent);
// check the response of savechanges to confirm that the operation was successful
if (db.SaveChanges() == 1)
return $"{{Added : {{Id: {maxId}, Name : {studentInfo.name}, RollNumber : {studentInfo.rollNumber}, Course : {studentInfo.course} }} }}";
return "An Error Occurred While adding data";
}
}
}
We have to create model (A simple class containing all the properties that will be received) for URL encoded data to store. The model used for above example is below:
namespace DbFirstApproach.Models
{
public class AddStudentModel
{
public int rollNumber { get; set; }
public string course { get; set; }
public string name { get; set; }
}
}