In this post I will explain how to CRUD Operations Using Entity Framework in APS.Net Core
Step1:- First open Visual studio and click on create a new project
Then Select ASP.NET Core Web App (Model View Controller)
Then Configure New Project like below screen
Then Select Additional Information
Then Right Click On project name and select Manage NuGet Package
Then Install this three packages that showing on below screen
- Microsoft.EntityFrameworkCore
2. Microsoft.EntityFrameworkCore.SqlServer
3. Microsoft.EntityFrameworkCore.Tools
Step2:- On This step just Right Click on Models Folder and add a new class Students.cs and past this below code
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ASP_CRUD.Models
{
public class Students
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Course { get; set; }
[Required]
public string Address { get; set; }
}
}
After That again Right click on Models folder and add new class CoderRajContext.cs and Post Below Code
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ASP_CRUD.Models
{
public class CoderRajContext : DbContext
{
public CoderRajContext(DbContextOptions<CoderRajContext> options)
: base(options)
{
}
public DbSet<Students> Student { get; set; }
}
}
Then add connectionstrings on appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": { "MyCon": "Data Source = LAPTOP-PCMAS9LI; Database=asp_crud; Trusted_Connection=True; MultipleActiveResultSets=True;User ID=sa;Password=123" }
}
Then Open Startup.cs and replace below method
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<CoderRajContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyCon")));
}
Make sure all library available on Startup.cs
using ASP_CRUD.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
Step3:- Now go to tools->NuGet Package Manager-> Package Manager Console and run this Below Command
add-migration First
update-database
After Run this two command Database and table created successfully
Step4:- Then right click on controller folder and add new controller StudentsController.cs and Past Below code
using ASP_CRUD.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ASP_CRUD.Controllers
{
public class StudentsController : Controller
{
private readonly CoderRajContext context;
public StudentsController(CoderRajContext context)
{
this.context = context;
}
public async Task<IActionResult> Index()
{
IQueryable<Students> StudentList = from p in context.Student select p;
List<Students> StudentsList = await StudentList.ToListAsync();
return View(StudentsList);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(Students students)
{
if(ModelState.IsValid)
{
context.Add(students);
await context.SaveChangesAsync();
//return RedirectToAction("Index");
}
return View();
}
public async Task<IActionResult> Details(int id)
{
Students studentById = await context.Student.FirstOrDefaultAsync(x => x.Id == id);
if(studentById==null)
{
return NotFound();
}
return View(studentById);
}
public async Task<IActionResult> Edit(int id)
{
Students studentById = await context.Student.FindAsync(id);
if (studentById == null)
{
return NotFound();
}
return View(studentById);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Students students)
{
if (ModelState.IsValid)
{
var studentById = await context.Student.Where(x => x.Id != students.Id).FirstOrDefaultAsync(x => x.Id == students.Id);
if (studentById != null)
{
ModelState.AddModelError("", "The page already exists.");
return View(students);
}
context.Update(students);
await context.SaveChangesAsync();
return RedirectToAction("Edit", new { id = students.Id });
}
return View(students);
}
public async Task<IActionResult> Delete(int id)
{
Students StudentId = await context.Student.FindAsync(id);
if (StudentId == null)
{
TempData["Error"] = "The page does not exist!";
}
else
{
context.Student.Remove(StudentId);
await context.SaveChangesAsync();
}
return RedirectToAction("Index");
}
}
}
Then right click on Index( ) method and add View
Then select Razor View
then send just like below image
Then view page create successfully add same as for Create, Details, Edit and Delete I also provide code below
Page Name:- View/Students/Index.cshtml
@model IEnumerable<ASP_CRUD.Models.Students>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Course)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Course)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Page Name:- View/Students/Create.cshtml
@model ASP_CRUD.Models.Students
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Students</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Course" class="control-label"></label>
<input asp-for="Course" class="form-control" />
<span asp-validation-for="Course" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Address" class="control-label"></label>
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Page Name:- View/Students/Details.cshtml
@model ASP_CRUD.Models.Students
@{
ViewData["Title"] = "Details";
}
<h1>Details</h1>
<div>
<h4>Students</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Name)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Course)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Course)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.Address)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Address)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
Page Name:- View/Students/Edit.cshtml
@model ASP_CRUD.Models.Students
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Students</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Course" class="control-label"></label>
<input asp-for="Course" class="form-control" />
<span asp-validation-for="Course" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Address" class="control-label"></label>
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Thanks If You have any query then comment I always with you