Read Data from Database with Entity Framework Core in ASP.NET Core Razor Pages

Create a database named LearnASPNETCoreRazorPagesWithRealApps. This database have a table: Product table as below:

USE LearnASPNETCoreRazorPagesWithRealApps

/* Table structure for table `product` */

GO
CREATE TABLE Product (
    Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
	Name varchar(250) NULL,
	Price money NULL,
	Quantity int NULL,
	Status bit NOT NULL
)

/* Dumping data for table `product` */
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('p01', 'Laptop 1', 100.0000, 2, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('p02', 'Computer 1', 3.0000, 2, 0)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('p03', N'Laptop 2', 300.0000, 5, 0)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('p04', N'Computer 2', 3.0000, 2, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('p05', N'Computer 3', 8.0000, 2, 1)




On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Use NuGet add libraries as below:

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Proxies




Open appsettings.json file and add connection string as below

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=LearnASPNETCoreRazorPagesWithRealApps;user id=sa;password=123456"
  }
}

Create new folder named Models. In Models folder, create new entity class as below:

Create new class named Product.cs as below:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    [Table("Product")]
    public class Product
    {
        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

        public decimal Price { get; set; }

        public int Quantity { get; set; }

        public bool Status { get; set; }
    }
}

In Models folder, create new class named DataContext.cs as below:

using Microsoft.EntityFrameworkCore;

namespace LearnASPNETCoreRazorPagesWithRealApps.Models
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
        {
        }

        public DbSet<Product> Products { get; set; }
    }
}




Open Startup.cs file and add new configurations as below:

using LearnASPNETCoreRazorPagesWithRealApps.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreRazorPagesWithRealApps
{
    public class Startup
    {
        public IConfiguration configuration { get; }

        public Startup(IConfiguration _configuration)
        {
            configuration = _configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddDbContext<DatabaseContext>(options => options.UseLazyLoadingProxies().UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc();
        }
    }
}

Select Views folder and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select Razor View Imports item and click Add button to Finish

In _ViewImports.cshtml file and TagHelpers library as below:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers




Create new folder named Pages. In this folder, create new Razor Page named Index as below:

using LearnASPNETCoreRazorPagesWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace LearnASPNETCoreRazorPagesWithRealApps.Pages
{
    public class IndexModel : PageModel
    {
        private DatabaseContext db;

        [BindProperty]
        public Product product { get; set; }

        public IndexModel(DatabaseContext _db)
        {
            db = _db;
        }

        public void OnGet()
        {
            product = new Product();
        }

        public void OnPost()
        {
            db.Products.Add(product);
            db.SaveChanges();
        }

    }
}
@page
@model LearnASPNETCoreRazorPagesWithRealApps.Pages.IndexModel

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Add Product</h3>
    <form method="post" asp-page="index">
        <table cellpadding="2" cellspacing="2">
            <tr>
                <td>Name</td>
                <td>
                    <input type="text" asp-for="product.Name" />
                </td>
            </tr>
            <tr>
                <td>Price</td>
                <td>
                    <input type="text" asp-for="product.Price" />
                </td>
            </tr>
            <tr>
                <td>Quantity</td>
                <td>
                    <input type="text" asp-for="product.Quantity" />
                </td>
            </tr>
            <tr>
                <td>Status</td>
                <td>
                    <input type="checkbox" asp-for="product.Status" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save" />
                </td>
            </tr>
        </table>
    </form>

</body>
</html>




Open Index Razor Page with following url: http://localhost:1115

Click Save button to save new product to database