Insert data into database using entity framework in ASP.NET Core using Visual Studio 2022 | Part 5

Опубликовано: 13 Март 2026
на канале: Syed Ali
205
0

Insert data into database using entity framework in ASP.NET Core using Visual Studio 2022:
Requirement: SQL server 2012, Visual studio 2022

SQL table:
CREATE TABLE emp_detail(
[emp_id] [int] IDENTITY(100,1) NOT NULL,
[emp_name] [nvarchar](100) NULL,
[address] [nvarchar](200) NULL,
CONSTRAINT [PK_emp_detail] PRIMARY KEY CLUSTERED
(
[emp_id] ASC
)
)

Steps-A)
Installation Required through NuGet packages
1) Microsoft.EntityFrameworkCore.SqlServer
2) microsoft.entityframeworkcore.tools
3) Microsoft.Extensions.Configuration


Steps-B)
i) Create a folder Models
ii)
Create a Class through the command line of NUget Package:
Scaffold-DbContext "Server=DESKTOP-HSSNFCU;Database=Sample_db;Trusted_Connection=True; TrustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
After running this command in the NUget Package console, then you will get the SampleDbContext class
SampleDbContext is a custom DbContext class used to interact with the database in an ASP.NET Core application.
It includes DbSet properties for each of the tables you want to interact with, and you can use it to perform CRUD operations. The class can be customized with methods like OnModelCreating to further refine how Entity Framework Core interacts with your database.

Steps-C) add db context into the programme file.
// add db context to the container
builder.Services.AddDbContext SampleDbContext ();

Steps-D) Need to added the Razor pages:
AddEmployee.cshtml

@page:
In ASP.NET Core, the @page directive is used in Razor Pages to mark a Razor Page as an endpoint that can handle HTTP requests.
When you use the @page directive, you're essentially turning a .cshtml file into an endpoint that can respond to requests, without needing an explicit controller action.
@model:
In ASP.NET Core, @model is a directive used in Razor views (whether in Razor Pages or MVC views) to specify the type of the model that the view will use.
This directive allows you to strongly type your view by binding it to a specific model class, enabling features like IntelliSense, validation, and access to model properties directly in the Razor view.
Handler Methods:
Instead of having controllers and actions like in MVC, Razor Pages uses handler methods.
These methods are defined in the page’s code-behind file (typically .cshtml.cs) and respond to HTTP requests (GET, POST, etc.)
In the page model (.cshtml.cs), you can define handler methods (like OnGet(), OnPost()) to handle HTTP requests.