Read Data from Database with Entity Framework Core in ASP.NET Core MVC 5

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

USE LearnASPNETCoreMVC5WithRealApps

/* 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('Name 1', 20.0000, 4, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 2', 12.0000, 8, 0)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 3', 4.0000, 3, 1)
GO
INSERT Product(Name, Price, Quantity, Status) VALUES('Name 4', 17.0000, 8, 1)




On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




Use NuGet add Libraries need for Entity Framework Core as below:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.SqlServer.Design
  • Microsoft.EntityFrameworkCore.Proxies
  • Microsoft.Extensions.Configuration.JSON

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

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

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public IConfiguration configuration;

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

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

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

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}




Select Project and right click to select Add\New Item Menu

Select Web\ASP.NET in left side. Select App Settings File item and click Add button to Finish

In appsettings.json file and new configurations as below:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=LearnASPNETCoreMVC5WithRealApps;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.Schema;

namespace LearnASPNETCoreMVC5.Models
{
    [Table("Product")]
    public class Product
    {
        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 LearnASPNETCoreMVC5.Models
{
    public class DataContext : DbContext
    {
        public DataContext()
        {
        }

        public DataContext(DbContextOptions<DataContext> options)
            : base(options)
        {
        }

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

    }
}




Create new folder named Controllers. In Controllers folder, create new controller named ProductController.cs as below:

using LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("product")]
    public class ProductController : Controller
    {
        private DataContext db;

        public ProductController(DataContext _db)
        {
            db = _db;
        }

        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            ViewBag.products = db.Products.ToList();
            return View();
        }

    }
}

In Views/Product folder, create new views as below:

Create new view named Index.cshtml as below:

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

    <h3>Product List</h3>
    <table border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Status</th>
        </tr>
        @foreach (var product in ViewBag.products)
        {
            <tr>
                <td>@product.Id</td>
                <td>@product.Name</td>
                <td>@product.Price</td>
                <td>@product.Quantity</td>
                <td>@product.Status</td>
            </tr>
        }
    </table>

</body>
</html>




Access Index action in Product controller with following url: http://localhost:9596/Product/Index

Output