ASP.NET如何配置数据库?详细步骤图文教程
- 技术教程
- 2026-02-09
- 2064
在 ASP.NET 中配置数据库连接主要涉及以下步骤(以 SQL Server 为例,其他数据库类似):
配置连接字符串
-
在 appsettings.json 中添加连接字符串
{ "ConnectionStrings": { "DefaultConnection": "Server=你的服务器地址;Database=你的数据库名;User Id=用户名;Password=密码;" // 示例(本地 SQL Server): // "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=MyDB;Trusted_Connection=True;" } } -
支持的数据库类型:
- SQL Server:Server=.;Database=MyDB;Integrated Security=True;
- MySQL:Server=localhost;Database=MyDB;Uid=root;Pwd=123456;
- SQLite:Data Source=MyDatabase.db;
- PostgreSQL:Host=localhost;Database=MyDB;Username=postgres;Password=123456;
载入数据库上下文(以 Entity Framework Core 为例)
-
安装 NuGet 包:
- SQL Server: Microsoft.EntityFrameworkCore.SqlServer
- MySQL: Pomelo.EntityFrameworkCore.MySql
- SQLite: Microsoft.EntityFrameworkCore.Sqlite
-
在 Program.cs 中注册 DbContext:
var builder = WebApplication.CreateBuilder(args); // 添加数据库上下文(根据数据库类型选择) builder.Services.AddDbContext<AppDbContext>(options => { // SQL Server options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")); // MySQL(使用 Pomelo 驱动) // options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(...)); // SQLite // options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")); });
创建 DbContext 类
public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // 定义数据表 public DbSet<User> Users { get; set; } } // 实体类示例 public class User { public int Id { get; set; } public string Name { get; set; } }
数据库迁移(Code First)
-
安装 EF Core 工具:

dotnet tool install --global dotnet-ef
-
创建迁移:

-
更新数据库:
dotnet ef database update -
生产环境连接字符串:
- 使用环境变量或密钥管理服务(如 Azure Key Vault)
- 在 Azure App Service 中通过“配置”>“连接字符串”设置
-
敏感信息保护:
# 使用 .NET 用户机密(开发环境) dotnet user-secrets set "ConnectionStrings:DefaultConnection" "你的连接字符串"
-
连接失败:
- 检查服务器是否可访问
- 验证用户名/密码是否正确
- 检查防火墙设置
-
迁移错误:
- 确保 DbContext 已载入
- 检查实体类与数据库表的映射
提示:对于不同数据库,只需替换连接字符串和对应的 EF Core 提供程序(UseSqlServer/UseMySql/UseSqlite),其他代码结构保持一致。
在控制器中使用数据库
public class UserController : Controller { private readonly AppDbContext _context; // 通过依赖载入获取上下文 public UserController(AppDbContext context) { _context = context; } public IActionResult Index() { var users = _context.Users.ToList(); return View(users); } }
不使用 EF Core 的原始 ADO.NET 连接
using System.Data.SqlClient; public class UserRepository { private readonly IConfiguration _config; public UserRepository(IConfiguration config) { _config = config; } public List<User> GetUsers() { var connectionString = _config.GetConnectionString("DefaultConnection"); using (var connection = new SqlConnection(connectionString)) { connection.Open(); var command = new SqlCommand("SELECT * FROM Users", connection); var reader = command.ExecuteReader(); var users = new List<User>(); while (reader.Read()) { users.Add(new User { Id = (int)reader["Id"], Name = (string)reader["Name"] }); } return users; } } }
安全注意事项
常见问题排查