1. Install Required Packages (.
NET 8
compatible)
dotnet add package [Link] --version 8.0.0
dotnet add package [Link] --version 8.0.0
dotnet add package [Link] --version 8.0.0
2. Create Model (Code First Class)
📁 Folder: Models/[Link]
namespace [Link]
{
public class Student
{
public int Id { get; set; } // Primary Key
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
}
3. Create DbContext
📁 Folder: Data/[Link]
using [Link];
using [Link];
namespace [Link]
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Student> Students { get; set; }
}
}
4. Add Connection String
📄 [Link]
{
"ConnectionStrings": {
"DefaultConnection":
"Server=.;Database=MvcDb;Trusted_Connection=True;TrustServerCertificate=True"
}
}
5. Register DbContext (.NET 8 [Link])
📄 [Link]
using [Link];
using [Link];
var builder = [Link](args);
[Link]();
// Register DbContext
[Link]<AppDbContext>(options =>
[Link](
[Link]("DefaultConnection")
)
);
var app = [Link]();
[Link]();
[Link]();
[Link](
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
[Link]();
6. Create Migration (Code First Step)
dotnet ef migrations add InitialCreate
7. Create Database
dotnet ef database update
✔ This will:
Create database MvcDb
Create Students table automatically
8. Controller (CRUD Basic)
📁 Controllers/[Link]
using [Link];
using [Link];
using [Link];
namespace [Link]
{
public class StudentController : Controller
{
private readonly AppDbContext _context;
public StudentController(AppDbContext context)
{
_context = context;
}
// READ
public IActionResult Index()
{
var students = _context.[Link]();
return View(students);
}
// CREATE (GET)
public IActionResult Create()
{
return View();
}
// CREATE (POST)
[HttpPost]
public IActionResult Create(Student student)
{
_context.[Link](student);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
}
9. View - [Link]
📁 Views/Student/[Link]
@model List<[Link]>
<h2>Student List</h2>
<a href="/Student/Create">Add Student</a>
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@[Link]</td>
<td>@[Link]</td>
<td>@[Link]</td>
<td>@[Link]</td>
</tr>
}
</table>
10. View - [Link]
@model [Link]
<h2>Add Student</h2>
<form method="post">
<input asp-for="Name" placeholder="Name" />
<br />
<input asp-for="Email" placeholder="Email" />
<br />
<input asp-for="Age" placeholder="Age" />
<br />
<button type="submit">Save</button>
</form>