Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
using
System;
System.ComponentModel.DataAnnotations;
System.ComponentModel.DataAnnotations.Schema;
namespace
StudentApplication.API.Models
{
public
class
Student
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
long
StudentId {
get
;
set
; }
string
FirstName {
LastName {
Gender {
DateTime? DateOfBirth {
DateTime? DateOfRegistration {
PhoneNumber {
Email {
Address1 {
Address2 {
City {
State {
Zip {
}
CREATE
DATABASE
StundentApplication
Microsoft.EntityFrameworkCore;
ApplicationContext: DbContext
ApplicationContext(DbContextOptions opts) :
base
(opts)
DbSet<Student> Students {
protected
override
void
OnConfiguring(DbContextOptionsBuilder optionsBuilder)
,
"ConnectionString"
: {
"StudentApplicationDB"
:
"Server=SSAI-L0028-HP\\SQLEXPRESS;Database=StundentApplication;Trusted_Connection=True;"
StudentApplication.API.Models;
StudentApplication.API.Models.DataManager;
StudentApplication.API.Models.Repository
ConfigureServices(IServiceCollection services)
// Add framework services.
services.AddDbContext<ApplicationContext>(opts => opts.UseSqlServer(Configuration[
"ConnectionString:StudentApplicationDB"
]));
services.AddSingleton(
typeof
(IDataRepository<Student,
>),
(StudentManager));
services.AddMvc();
PM> Add-Migration StudentApplication.API.Models.ApplicationContext
PM> update-database
System.Collections.Generic;
interface
IDataRepository<TEntity, U> where TEntity :
IEnumerable<TEntity> GetAll();
TEntity Get(U id);
Add(TEntity b);
Update(U id, TEntity b);
Delete(U id);
StudentApplication.API.Models.Repository;
System.Linq;
StudentApplication.API.Models.DataManager
StudentManager : IDataRepository<Student,
>
ApplicationContext ctx;
StudentManager(ApplicationContext c)
ctx = c;
Student Get(
id)
var student = ctx.Students.FirstOrDefault(b => b.StudentId == id);
return
student;
IEnumerable<Student> GetAll()
var students = ctx.Students.ToList();
students;
Add(Student stundent)
ctx.Students.Add(stundent);
studentID = ctx.SaveChanges();
studentID;
Delete(
int
studentID = 0;
if
(student !=
null
)
ctx.Students.Remove(student);
Update(
id, Student item)
var student = ctx.Students.Find(id);
student.FirstName = item.FirstName;
student.LastName = item.LastName;
student.Gender = item.Gender;
student.PhoneNumber = item.PhoneNumber;
student.Email = item.Email;
student.DateOfBirth = item.DateOfBirth;
student.DateOfRegistration = item.DateOfRegistration;
student.Address1 = item.Address1;
student.Address2 = item.Address2;
student.City = item.City;
student.State = item.State;
student.Zip = item.Zip;
System.Threading.Tasks;
Microsoft.AspNetCore.Mvc;
StudentApplication.API.Controllers
[Route(
"api/[controller]"
)]
StudentController : Controller
private
IDataRepository<Student,
> _iRepo;
StudentController(IDataRepository<Student,
> repo)
_iRepo = repo;
// GET: api/values
[HttpGet]
IEnumerable<Student> Get()
_iRepo.GetAll();
// GET api/values/5
[HttpGet(
"{id}"
_iRepo.Get(id);
// POST api/values
[HttpPost]
Post([FromBody]Student student)
_iRepo.Add(student);
[HttpPut]
Put([FromBody]Student student)
_iRepo.Update(student.StudentId,student);
// DELETE api/values/5
[HttpDelete(
_iRepo.Delete(id);
System.Net.Http;
System.Net.Http.Headers;
StudentApplication.Web.Helper
StudentAPI
_apiBaseURI =
"http://localhost:60883"
HttpClient InitializeClient()
var client =
new
HttpClient();
//Passing service base url
client.BaseAddress =
Uri(_apiBaseURI);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(
MediaTypeWithQualityHeaderValue(
"application/json"
));
client;
StudentDTO
Newtonsoft.Json;
StudentApplication.Web.Helper;
System.Text;
StudentApplication.Web.Controllers
StudentsController : Controller
StudentAPI _studentAPI =
StudentAPI();
async Task<IActionResult> Index()
List<StudentDTO> dto =
List<StudentDTO>();
HttpClient client = _studentAPI.InitializeClient();
HttpResponseMessage res = await client.GetAsync(
"api/student"
);
//Checking the response is successful or not which is sent using HttpClient
(res.IsSuccessStatusCode)
//Storing the response details received from web api
var result = res.Content.ReadAsStringAsync().Result;
//Deserializing the response received from web api and storing into the Employee list
dto = JsonConvert.DeserializeObject<List<StudentDTO>>(result);
//returning the employee list to view
View(dto);
// GET: Students/Create
IActionResult Create()
View();
// POST: Students/Create
[ValidateAntiForgeryToken]
IActionResult Create([Bind(
"StudentId,FirstName,LastName,Gender,DateOfBirth,DateOfRegistration,PhoneNumber,Email,Address1,Address2,City,State,Zip"
)] StudentDTO student)
(ModelState.IsValid)
var content =
StringContent(JsonConvert.SerializeObject(student), Encoding.UTF8,
HttpResponseMessage res = client.PostAsync(
, content).Result;
RedirectToAction(
"Index"
View(student);
// GET: Students/Edit/1
async Task<IActionResult> Edit(
? id)
(id ==
NotFound();
var student = dto.SingleOrDefault(m => m.StudentId == id);
(student ==
// POST: Students/Edit/1
IActionResult Edit(
id, [Bind(
(id != student.StudentId)
HttpResponseMessage res = client.PutAsync(
// GET: Students/Delete/1
async Task<IActionResult> Delete(
// POST: Students/Delete/5
[HttpPost, ActionName(
"Delete"
IActionResult DeleteConfirmed(
HttpResponseMessage res = client.DeleteAsync($
"api/student/{id}"
).Result;
@model IEnumerable<
StudentApplication.Web.Helper.StudentDTO
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
<
h2
>Index</
p
a
asp-action
=
"Create"
>Create New</
</
table
"table"
thead
tr
th
@Html.DisplayNameFor(model => model.FirstName)
@Html.DisplayNameFor(model => model.LastName)
@Html.DisplayNameFor(model => model.Gender)
@Html.DisplayNameFor(model => model.DateOfBirth)
@Html.DisplayNameFor(model => model.DateOfRegistration)
@Html.DisplayNameFor(model => model.PhoneNumber)
@Html.DisplayNameFor(model => model.Email)
@Html.DisplayNameFor(model => model.Address1)
@Html.DisplayNameFor(model => model.Address2)
@Html.DisplayNameFor(model => model.City)
@Html.DisplayNameFor(model => model.State)
@Html.DisplayNameFor(model => model.Zip)
></
tbody
@foreach (var item in Model)
td
@Html.DisplayFor(modelItem => item.FirstName)
@Html.DisplayFor(modelItem => item.LastName)
@Html.DisplayFor(modelItem => item.Gender)
@Html.DisplayFor(modelItem => item.DateOfBirth)
@Html.DisplayFor(modelItem => item.DateOfRegistration)
@Html.DisplayFor(modelItem => item.PhoneNumber)
@Html.DisplayFor(modelItem => item.Email)
@Html.DisplayFor(modelItem => item.Address1)
@Html.DisplayFor(modelItem => item.Address2)
@Html.DisplayFor(modelItem => item.City)
@Html.DisplayFor(modelItem => item.State)
@Html.DisplayFor(modelItem => item.Zip)
"Edit"
asp-route-id
"@item.StudentId"
>Edit</
> |
"Details"
>Details</
>Delete</
@model StudentApplication.Web.Helper.StudentDTO
ViewData["Title"] = "Create";
>Create</
form
div
"form-horizontal"
h4
>Student</
hr
/>
asp-validation-summary
"ModelOnly"
"text-danger"
"form-group"
label
asp-for
"FirstName"
"col-md-2 control-label"
"col-md-10"
input
"form-control"
span
asp-validation-for
"LastName"
"Gender"
"DateOfBirth"
"DateOfRegistration"
"PhoneNumber"
"Email"
"Address1"
"Address2"
"City"
"State"
"Zip"
"col-md-offset-2 col-md-10"
type
"submit"
value
"btn btn-default"
>Back to List</
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
ViewData["Title"] = "Edit";
"hidden"
"StudentId"
"Save"
ViewData["Title"] = "Delete";
h3
>Are you sure you want to delete this?</
dl
"dl-horizontal"
dt
dd
@Html.DisplayFor(model => model.FirstName)
@Html.DisplayFor(model => model.LastName)
@Html.DisplayFor(model => model.Gender)
@Html.DisplayFor(model => model.DateOfBirth)
@Html.DisplayFor(model => model.DateOfRegistration)
@Html.DisplayFor(model => model.PhoneNumber)
@Html.DisplayFor(model => model.Email)
@Html.DisplayFor(model => model.Address1)
@Html.DisplayFor(model => model.Address2)
@Html.DisplayFor(model => model.City)
@Html.DisplayFor(model => model.State)
@Html.DisplayFor(model => model.Zip)
"form-actions no-color"
/> |