Step 1: Create a New Project
Open Visual Studio 2022.
Click Create a new project.
Select ASP.NET Core Web App (Model-View-Controller) → Next.
Name it ProductCRUD → Choose a location → Next.
Select .NET 7 or .NET 8 (latest installed) → Create.
Leave authentication as None for simplicity → Create.
Step 2: Install EF Core
Right-click your project in Solution Explorer → Manage NuGet Packages.
Install:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Step 3: Create the Model
Right-click Models → Add → Class → Name it Product.cs.
Add:
using System.ComponentModel.DataAnnotations;
namespace ProductCRUD.Models
{
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(0, 10000)]
public decimal Price { get; set; }
}
}Step 4: Create the Database Context
Right-click Data (create folder if needed) → Add → Class → ApplicationDbContext.cs.
Add:
using Microsoft.EntityFrameworkCore;
using ProductCRUD.Models;
namespace ProductCRUD.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
}Step 5: Configure the Database
Open appsettings.json and add the connection string:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=ProductDB;Trusted_Connection=True;MultipleActiveResultSets=true"
}Open Program.cs and add:
using Microsoft.EntityFrameworkCore;
using ProductCRUD.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Products}/{action=Index}/{id?}");
app.Run();Step 6: Scaffold the Controller and Views
Right-click Controllers → Add → Controller.
Choose MVC Controller with views, using Entity Framework → Add.
Set:
Model class: Product
Data context: ApplicationDbContext
Controller name: ProductsController
Join the conversation! Your thoughts help the community grow.