Post

ASP.net Hands-on Web site with CRUD function (#1 Database and Read)

I am going to make a web site show a Blood Pressure measurement. The first step is to connect Database server and show a default seed data.

  1. create .net core MVC project without https checking
  2. Add the Microsoft.EntityFrameworkCore packages

1

it should match with the project framework version. (7.0.15)

2

  1. Create DBContext

3

  1. Define a class to use as Database schema
1
2
3
4
5
6
7
8
9
10
11
12
namespace BPMeasurement.Entities
{
	public class BloodPressure
	{
		public int BloodPressureId { get; set; }
		public int Systolic { get; set; }
		public int Diastolic { get; set; }
		public string Category { get; set; }
		public string Position { get; set; }
		public string DateTime { get; set; }
	}
}
  1. Define BPDbContext class that inherits the DbContext seed initial data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using Microsoft.EntityFrameworkCore;

namespace BPMeasurement.Entities
{
    public class BPDbContext : DbContext
	{
		public BPDbContext(DbContextOptions<BPDbContext> option) : base(option)
		{
		}

		public DbSet<BloodPressure> BloodPressures { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<BloodPressure>().HasData(
                new BloodPressure() { BPId = 1, Systolic=120, Diastolic=80, Category="Normal", Position="Sitting", DateTime="1996-02-09"},
                new BloodPressure() { BPId = 2, Systolic = 122, Diastolic = 79, Category = "Normal", Position = "Sitting", DateTime = "1996-02-09" },
                new BloodPressure() { BPId = 3, Systolic = 130, Diastolic = 85, Category = "Normal", Position = "Sitting", DateTime = "1996-02-09" }
               );
        }
    }
}
  1. Declare “ConnectonString” on appsettings.json
1
2
3
4
5
"ConnectionStrings": {
    "MovieConnectionString": "Server=tcp:127.0.0.1,1433;Database=BloodPressure;
		 User Id=sa;Password=Abc123456@;Integrated security=False;
			MultipleActiveResultSets=true;TrustServerCertificate=true"
  }
  1. add services to connect database server on program.cs
1
2
3
4
5
6
7
using Microsoft.EntityFrameworkCore;
using BPMeasurement.Entities;

...

var connstr = builder.Configuration.GetConnectionString("BloodPressureConnectionString");
builder.Services.AddDbContext<BPDbContext>(option => option.UseSqlServer(connstr));
  1. Install SqlServer and Design package on Nuget Package Manager Console
1
2
3
4
5
6
7
8
PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer -v 7.0.15
PM > Install-Package Microsoft.EntityFrameworkCore.Design -v 7.0.15
// without version, it will be the lastest version (cause an error)

or

dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  1. PM> Add-Migration Initial to commit a default database and its seed.

be sure if you have a primary key for Id.

the naming convention for Id is “Id” or “ClassName+Id”

1
2
3
public class BloodPressure
	{
		public int BloodPressureId { get; set; }
1
2
3
4
PM> Add-Migration Initial
Build started...
Build succeeded.
To undo this action, use Remove-Migration.
  1. PM> Update-Database
1
2
3
4
5
6
7
8
9
10
Build started...
Build succeeded.
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (216ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
,,,
Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
      VALUES (N'20240207172129_Initial', N'7.0.15');
Done.

4

  1. BPController.cs to get all list at first. (add controller)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace BPMeasurement.Controllers
{
    public class BPController : Controller
    {
        private BPDbContext _bpDbContext;

        public BPController(BPDbContext bpDbContext)
        {
            _bpDbContext = bpDbContext;
        }

        public IActionResult List()
        {
            List<BloodPressure> bPressures = _bpDbContext.BloodPressures.OrderBy(m => m.DateTime).ToList();
            return View(bPressures);
        }
    }
}
  1. add @using BPMeasurement.Entities in _ViewImport.cshtml to use Model in html pages.
  2. make list page to call all list.

5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@using BPMeasurement.Entities
@model List<BloodPressure>
@{ViewData["Title"] = "All Blood Pressure data";
}
<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>Reading</th>
            <th>Category</th>
            <th>Position</th>
            <th>Data Taken</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach(BloodPressure bp in Model)
        {
            <tr>
                <td>@bp.Systolic/@bp.Diastolic</td>
                <td>@bp.Category</td>
                <td>@bp.Position</td>
                <td>@bp.DateTime</td>

                <td>
                    <a href="#">Edit</a>
                    <span class="mx-1">|</span>
                    <a href="#">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>
This post is licensed under CC BY 4.0 by the author.