在 .NET Core 中从 SQL Server 数据库读取数据,通常使用 Entity Framework Core (EF Core) 或 ADO.NET。以下是两种方式的详细实现步骤和示例代码。

1. 使用 Entity Framework Core (EF Core)
EF Core 是一个 ORM(对象关系映射)框架,可以简化数据库操作。

1.1 安装 EF Core
通过 NuGet 安装以下包:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design

1.2 定义数据模型
创建一个与数据库表对应的模型类。

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

1.3 创建数据库上下文
继承 DbContext 并定义 DbSet 属性。

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=localhost;Database=MyDatabase;User Id=sa;Password=your_password;");
    }
}

1.4 读取数据
在控制器或服务中读取数据。

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly AppDbContext _context;

    public ProductsController(AppDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        var products = _context.Products.ToList(); // 读取所有产品
        return Ok(products);
    }
}

2. 使用 ADO.NET
ADO.NET 是一种更底层的数据库访问方式,适合需要直接控制 SQL 查询的场景。

2.1 安装依赖
通过 NuGet 安装以下包:

dotnet add package System.Data.SqlClient

2.2 读取数据
使用 SqlConnection 和 SqlCommand 执行查询。

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly string _connectionString = "Server=localhost;Database=MyDatabase;User Id=sa;Password=your_password;";

    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        var products = new List<Product>();

        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            var command = new SqlCommand("SELECT Id, Name, Price FROM Products", connection);

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    products.Add(new Product
                    {
                        Id = reader.GetInt32(0),
                        Name = reader.GetString(1),
                        Price = reader.GetDecimal(2)
                    });
                }
            }
        }

        return Ok(products);
    }
}

3. 使用 Dapper
Dapper 是一个轻量级的 ORM,性能接近 ADO.NET,但使用更简单。

3.1 安装 Dapper
通过 NuGet 安装:

dotnet add package Dapper

3.2 读取数据

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Dapper;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly string _connectionString = "Server=localhost;Database=MyDatabase;User Id=sa;Password=your_password;";

    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            var products = connection.Query<Product>("SELECT Id, Name, Price FROM Products");
            return Ok(products);
        }
    }
}

4. 性能与选择建议

方式 优点 缺点 适用场景
EF Core 开发效率高,支持 LINQ 性能略低,学习曲线较陡 快速开发,复杂查询
ADO.NET 性能高,直接控制 SQL 代码量大,维护成本高 高性能需求,简单查询
Dapper 性能高,使用简单 不支持 LINQ,功能较少 高性能需求,简单 ORM 功能

5. 连接字符串配置
将连接字符串存储在 appsettings.json 中,避免硬编码:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=MyDatabase;User Id=sa;Password=your_password;"
  }
}

在 Startup.cs 中读取配置:

public void ConfigureServices(IServiceCollection services)
{
    var connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(connectionString));
}

总结
在 .NET Core 中,可以通过以下方式从 SQL Server 读取数据:

EF Core:适合快速开发和复杂查询。

ADO.NET:适合高性能需求和直接控制 SQL。

Dapper:轻量级 ORM,性能接近 ADO.NET。

根据项目需求选择合适的方式,并结合连接字符串配置,确保代码的可维护性和安全性。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐