在 ASP.NET 中访问数据库有多种方式,以下是几种主流方法和详细步骤(以 SQL Server 为例):

ADO.NET(底层直接访问)
核心步骤:
-
添加命名空间
using System.Data.SqlClient; // .NET Framework // 或 using Microsoft.Data.SqlClient; // .NET Core+ (推荐)
-
配置连接字符串
- 在
Web.config(ASP.NET) 或appsettings.json(ASP.NET Core) 中添加:<!-- Web.config --> <connectionStrings> <add name="MyDb" connectionString="Server=服务器地址;Database=数据库名;User Id=用户名;Password=密码;" providerName="System.Data.SqlClient"/> </connectionStrings>// appsettings.json (.NET Core) { "ConnectionStrings": { "MyDb": "Server=.;Database=MyDB;Integrated Security=True;" } }
- 在
-
执行数据库操作
// 读取数据示例 string connectionString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString; // .NET Core: 通过依赖注入获取 IConfiguration,再取 connectionString using (SqlConnection conn = new SqlConnection(connectionString)) { string sql = "SELECT * FROM Products"; SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { string productName = reader["ProductName"].ToString(); // 处理数据... } }
Entity Framework Core(推荐 ORM)
步骤:
-
安装 NuGet 包
Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.Design -
创建数据模型
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } -
创建 DbContext

public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } } -
配置依赖注入(Startup.cs)
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDb"))); } -
在控制器中使用
public class ProductController : Controller { private readonly AppDbContext _context; public ProductController(AppDbContext context) { _context = context; // 依赖注入 } public IActionResult Index() { var products = _context.Products.ToList(); return View(products); } }
Dapper(轻量级 ORM)
步骤:
-
安装 NuGet 包
Install-Package Dapper Install-Package System.Data.SqlClient -
执行查询
using Dapper; using System.Data; public IEnumerable<Product> GetProducts() { using (IDbConnection db = new SqlConnection(connectionString)) { return db.Query<Product>("SELECT * FROM Products"); } }
关键注意事项
-
安全防护
- 防 SQL 注入:使用参数化查询(ADO.NET 的
SqlParameter/ Dapper 的参数化 / EF Core 的 LINQ)。// ADO.NET 参数化示例 SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username = @User", conn); cmd.Parameters.AddWithValue("@User", userInput);
- 防 SQL 注入:使用参数化查询(ADO.NET 的
-
连接管理

- 使用
using语句确保连接关闭(如上文示例)。
- 使用
-
配置管理
- 不要硬编码连接字符串,始终从配置文件读取。
-
异步操作(提升性能)
// EF Core 异步示例 var products = await _context.Products.ToListAsync(); // Dapper 异步示例 var products = await db.QueryAsync<Product>("SELECT * FROM Products");
各方案对比
| 方法 | 优点 | 适用场景 |
|---|---|---|
| ADO.NET | 高性能,完全控制 SQL | 需要精细控制 SQL/存储过程 |
| EF Core | 开发快,强类型,迁移支持 | 快速开发,复杂对象关系 |
| Dapper | 高性能,简单易用 | 读写频繁的轻量级应用 |
根据项目需求选择合适的技术栈,新项目推荐 EF Core 或 Dapper,遗留系统可使用 ADO.NET。
图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/287874.html

