在ASP.NET Core 中连接数据库需要以下步骤:
- 安装数据库提供者包
对于不同的数据库,需要安装相应的包:SQL Server: Microsoft.EntityFrameworkCore.SqlServerMySQL: Pomelo.EntityFrameworkCore.MySqlPostgreSQL: Npgsql.EntityFrameworkCore.PostgreSQLSQLite: Microsoft.EntityFrameworkCore.Sqlite - 配置连接字符串
在appsettings.json中添加连接字符串: - json
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
- 定义数据模型
创建表示数据库表的实体类: - csharp
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
- 创建数据库上下文
继承DbContext并配置实体: - csharp
using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } }
- 注册数据库上下文
在Program.cs中注册数据库上下文和连接字符串: - csharp
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
- 使用依赖注入访问数据库
在控制器中通过构造函数注入数据库上下文: - csharp
private readonly ApplicationDbContext _context; public ProductsController(ApplicationDbContext context) { _context = context; }
- 执行数据库操作
使用 DbContext 执行 CRUD 操作: - csharp
// 获取所有产品
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { return await _context.Products.ToListAsync(); } // 创建新产品 [HttpPost] public async Task<ActionResult<Product>> PostProduct(Product product) { _context.Products.Add(product); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); }
完整示例代码
下面是一个完整的 SQL Server 数据库连接示例:
csharp
// Program.cs
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// 添加数据库上下文
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// 添加控制器
builder.Services.AddControllers();
// 添加Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// 配置开发环境使用Swagger
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
// Models/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
}
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
}
其他数据库连接示例
MySQL 连接
csharp
// Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(
builder.Configuration.GetConnectionString("DefaultConnection"),
ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("DefaultConnection"))
)
);
// appsettings.json
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user=root;password=yourpassword;database=mydatabase"
}
PostgreSQL 连接
csharp
// Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection"))
);
// appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=mydatabase;Username=postgres;Password=yourpassword"
}
SQLite 连接
csharp
// Program.cs
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"))
);
// appsettings.json
"ConnectionStrings": {
"DefaultConnection": "Data Source=MyDatabase.db"
}
根据你的需求选择合适的数据库提供者,并相应地配置连接字符串和 DbContext。