在razor页面上读写数据库(我的Blazor学习二)
代码环境:VS2022,SQLserver express 2022 , SSMS2022。花了半个小时安装了微软数据库全套,express+管理端SSMS2022,都是免费的,nice. 把SQLserver设置成sa登录,因为我们EFcore要用sa用户连接数据库。SQLserver要配置一下网络端口1433,随便把防火墙关一下。

新建一个自己的数据库,里面新建一个自己的表:我们就在这个表上读写。在VS2022微软自带的Blazor server模式示例代码中,增加EFcore并开始使用:
1、NuGet中增加 EFcore类库,注意这些类库的大版本是和.net的大版本是对应的,不能乱用。
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
2、一句话按数据库表创建实体类,以后如果数据库字段变动,还是这一句话更新,加上 -Force,注意项目文件全部编译正确后,是每次都能成功覆盖更新的。
Scaffold-DbContext -Connection "TrustServerCertificate=True;Server=localhost;Database=RPA;User Id=sa;Password=pass;" Microsoft.EntityFrameworkCore.SqlServer -o Models 
EF core自动新建了实体类文件,同WinForm项目没有区别。接下来,我们在Program.cs文件中加入数据库工厂。只一行代码。builder.Services.AddDbContextFactory<JamesDbContext>();

然后就可以在razor文件中引入使用:注意,要把实体类库using声明进来

后面就是直接像winform一样使用LINQ了

我把页面设置为:@rendermode InteractiveServer 模式,每次点击新增和删除按钮,数据库的数据新增和删除后立即在页面上更新显示了。

全部Weather.razor页面代码:
@page "/weather"
@using BlazorApp1.Models@attribute [StreamRendering]
@rendermode InteractiveServer@inject JamesDbContext db<PageTitle>Weather</PageTitle>
<h1>Weather</h1>
<p>This component demonstrates showing data.</p>
<button class="btn btn-primary" @onclick="click_new">New</button>
<button class="btn btn-primary" @onclick="click_del">Delete</button>@if (db.Table1s == null)
{ <p><em>Loading...</em></p>}
else
{<table class="table"><thead><tr><th>日期</th><th>物料</th><th>价格</th></tr></thead><tbody>@foreach (var forecast in db.Table1s){<tr><td>@forecast.Id</td><td>@forecast.Aaa</td><td>@forecast.Bbb</td></tr>}</tbody></table>
}@code
{protected override async Task OnInitializedAsync(){// Simulate asynchronous loading to demonstrate streaming renderingawait Task.Delay(500); }private void click_new(){Table1 one = new Table1(){ Aaa = "w",Bbb = "0" };db.Table1s.Add(one);db.SaveChanges();}private void click_del(){ db.Table1s.Remove(db.Table1s.First());db.SaveChanges();}private void click_edit(){ }}