ASP.NET Core Razor Pages应用如何从SQL Server数据库检索数据
实现步骤
你执行scaffold-DbContext时已经自动生成了实体和对应DbContext,按下面步骤配置即可完成数据查询:
- 检查连接字符串配置
打开项目根目录的appsettings.json,确认ConnectionStrings节点下的SQL Server连接字符串正确,参考格式:
{ "ConnectionStrings": { "DefaultConnection": "Server=你的SQL Server实例地址;Database=你的数据库名;TrustServerCertificate=True;Integrated Security=True;" }, // 其他配置... }
如果是SQL Server账号密码认证,把Integrated Security=True替换为User Id=你的数据库账号;Password=你的数据库密码即可。
- 注册DbContext到依赖注入容器
打开项目根目录的Program.cs(.NET 6及以上版本),添加服务注册代码,注意替换成你实际生成的DbContext类名:
// 其他服务注册代码... builder.Services.AddDbContext<你生成的DbContext类名>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); var app = builder.Build(); // 其他中间件配置...
如果编译提示找不到UseSqlServer方法,手动安装对应版本的Microsoft.EntityFrameworkCore.SqlServer Nuget包即可,正常scaffold流程会自动引入这个依赖。
- 确认DbContext包含Employee的DbSet配置
打开自动生成的DbContext类,确认类中存在如下属性,没有的话手动补上:
public DbSet<Employee> Employees { get; set; }
- 在Razor Page中注入DbContext查询数据
Razor Pages通过构造函数注入获取DbContext实例,以员工列表页为例,在Index.cshtml.cs中编写如下代码:
public class IndexModel : PageModel { private readonly 你生成的DbContext类名 _context; // 构造函数注入DbContext public IndexModel(你生成的DbContext类名 context) { _context = context; } // 绑定查询结果,供前端页面调用 public IList<Employee> EmployeeList { get; set; } public async Task OnGetAsync() { // 常用查询示例 // 1. 查询所有状态为1的员工,异步查询不阻塞请求线程 EmployeeList = await _context.Employees .Where(e => e.Status == 1) .ToListAsync(); // 2. 根据主键查询单个员工 // var singleEmp = await _context.Employees.FindAsync(Guid.Parse("对应员工ID")); // 3. 投影查询,只取需要的字段,降低数据库传输开销 // var empSimpleInfo = await _context.Employees // .Select(e => new { e.Name, e.Address }) // .ToListAsync(); } }
在对应的前端页面Index.cshtml中,即可遍历绑定的列表渲染数据:
@page @model IndexModel <h3>员工列表</h3> <table> <thead> <tr> <th>姓名</th> <th>地址</th> <th>状态</th> </tr> </thead> <tbody> @foreach (var emp in Model.EmployeeList) { <tr> <td>@emp.Name</td> <td>@emp.Address</td> <td>@emp.Status</td> </tr> } </tbody> </table>
注意:Web场景下所有数据库操作优先使用EF Core提供的异步方法(带Async后缀),避免阻塞请求线程影响服务吞吐量。
内容的提问来源于stack exchange,提问作者Janki Dave
相关产品推荐
相关产品推荐

