blazor连接sql server
时间: 2025-08-09 20:59:57 浏览: 5
在 Blazor 应用中连接 SQL Server 数据库需要根据应用的类型(Blazor Server 或 Blazor WebAssembly)进行不同的处理。以下分别介绍两种方式的实现方法。
### Blazor Server 应用连接 SQL Server 数据库
Blazor Server 应用运行在服务器端,因此可以直接使用 .NET 的数据库访问技术,例如 Entity Framework Core 或 ADO.NET。
1. **配置连接字符串**
在 `appsettings.json` 文件中添加 SQL Server 的连接字符串,例如:
```json
{
"ConnectionStrings": {
"DefaultConnection": "Server=your_server;Database=your_database;User Id=your_user;Password=your_password;"
}
}
```
2. **注册数据库上下文**
在 `Program.cs` 文件中注册 Entity Framework Core 的数据库上下文:
```csharp
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
```
3. **使用数据库上下文**
在 Razor 组件中注入数据库上下文并执行查询操作:
```csharp
@inject ApplicationDbContext DbContext
@code {
private List<Product> products = new List<Product>();
protected override async Task OnInitializedAsync()
{
products = await DbContext.Products.ToListAsync();
}
}
```
### Blazor WebAssembly 应用连接 SQL Server 数据库
Blazor WebAssembly 应用运行在浏览器中,无法直接连接 SQL Server 数据库,必须通过后端 API 进行交互。
1. **创建 ASP.NET Core API 项目**
创建一个 ASP.NET Core 项目,并在其中配置 Entity Framework Core 来连接 SQL Server 数据库。
2. **配置连接字符串**
在 `appsettings.json` 文件中添加 SQL Server 的连接字符串:
```json
{
"ConnectionStrings": {
"DefaultConnection": "Server=your_server;Database=your_database;User Id=your_user;Password=your_password;"
}
}
```
3. **注册数据库上下文**
在 `Program.cs` 文件中注册数据库上下文:
```csharp
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
```
4. **创建 API 控制器**
添加一个控制器来处理前端请求:
```csharp
[ApiController]
[Route("[controller]")]
public class ProductController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetProducts()
{
var products = await _context.Products.ToListAsync();
return Ok(products);
}
}
```
5. **在 Blazor WebAssembly 中调用 API**
在 Blazor WebAssembly 项目中使用 `HttpClient` 调用 API:
```csharp
@inject HttpClient Http
@code {
private List<Product> products = new List<Product>();
protected override async Task OnInitializedAsync()
{
products = await Http.GetFromJsonAsync<List<Product>>("api/product");
}
}
```
通过以上方法,可以在 Blazor Server 或 Blazor WebAssembly 应用中实现与 SQL Server 数据库的连接[^1]。
---
###
阅读全文
相关推荐




















