ASP.NET Core

Model binding in Razor pages Using Database in .Net Core

Model binding in Razor pages Using Database in .Net Core

Model binding in Razor pages Using Database

Create a New Asp.net Core Web App

Project is created with following structure




Lets Add funcationality for Products in Ecommerces Portal

Step 1: Add a Data Model
In Solution Explorer, Right click on the project, Add > New Folder. Name the folder Models.
Right-click the Models folder. Select Add > Class. Name the class Product.


Step 2: Scaffold the product model
1. Right-click on the Pages folder > Add > New Folder.
2. Name the folder Products.
3. Right-click on the Pages/Products folder > Add > New Scaffolded Item.
4. In the Add New Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.


Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
In the Model class drop down, select Product


In the Data context class row, select the + (plus) sign.
A. In the Add Data Context dialog, the class is generated rename it as ProductsContext.


B. Select Add.


The scaffold process The scaffold process did following: -
Add all required packages, Update all dependencies, and generate Scaffold necessary code
creates the following folders and files:
A. Pages/Products: Create, Delete, Details, Edit, and Index.
B. Data/ProductsContext.cs

public class ProductsContext : DbContext
{
    public ProductsContext (DbContextOptions<ProductsContext> options)
        : base(options)
    {
    }

    public DbSet<FirstCoreWebApplication.Models.Product> Product { get; set; } = default!;
}


C. Adds the following highlighted code to the Program.cs file:

using FirstCoreWebApplication.Models;
//Added
using Microsoft.EntityFrameworkCore;
//Added
using Microsoft.Extensions.DependencyInjection;
//Added
using FirstCoreWebApplication.Data;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

//Added
builder.Services.AddDbContext<ProductsContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("ProductsContext") ?? throw new InvalidOperationException("Connection string 'ProductsContext' not found.")));


builder.Services.AddTransient<List<Users>>();

var app = builder.Build();



Step 3: Change connection string appsettings.development.json file

"ConnectionStrings": {
    "ProductsContext": "Server=WIN-AG8G6Q6DMJ2\\MSSQL17DEV;Database=Products;
Trusted_Connection=True;MultipleActiveResultSets=true"
}
Or with full details
"ConnectionStrings": {
    "ProductsContext": "Server=WIN-AG8G6Q6DMJ2\\MSSQL17DEV;Database=Products;User Id=sa;
password=!!Sql!!;Trusted_Connection=false;MultipleActiveResultSets=true"
},



Step 4: Create the initial database schema using EF's migration feature
The migrations feature in Entity Framework Core provides a way to:
- Create the initial database schema.
- Incrementally update the database schema to keep it in sync with the app's data model. Existing data in the database is preserved.

Open Package Manager Console
Tools menu, select NuGet Package Manager > Package Manager Console
In the PMC, enter the following commands:

Add-Migration InitialCreate
Update-Database

- The Add-Migration command generates code to create the initial database schema. The schema is based on the model specified in DbContext. The InitialCreate argument is used to name the migration.
- The Update-Database command runs the Up method in migrations that have not been applied. In this case, the command runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.


Test the app
Run the app and append /Products and enter (http://localhost:port/products)
Test the Create New link.
Test the Edit, Details, and Delete links.



Note:-

Razor Pages are derived from PageModel. By convention, the PageModel derived class is named PageNameModel
When the return type is IActionResult or Task<IActionResult>, a return statement must be provided.

The @page directive
The @page Razor directive makes the file an MVC action, which means that it can handle requests. @page must be the first Razor directive on a page.

The @model directive
The @model directive specifies the type of the model passed to the Razor Page.
The ProductsContext object handles the task of connecting to the database and mapping Product objects to database records.




Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram