首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C# 三層架構中數據庫查詢結果如何優雅返回:從 DataReader 到實體類的完整範例

     編輯:程式設計綜合問答

場景痛點

初學者常糾結:DAL 層查詢數據後,怎麼把 SqlDataReader 的結果「返回」給 BLL,再傳給 UI?是返回 DataTable、List<Dictionary> 還是自定義實體類?

推薦做法:返回強類型實體類或集合

定義實體類對應表結構,DAL 封裝 SqlDataReader 填充實體,返回 T 或 List<T>,上層調用極其清晰。

完整代碼範例

1. 實體類

public class Nation
{
    public int Id { get; set; }
    public string NationName { get; set; }
}

2. DAL 層:單條查詢返回實體

public Nation GetByName(string name)
{
    const string sql = "SELECT Id, NationName FROM TB_Nation WHERE NationName = @name";
    Nation nation = null;

    using (var conn = new SqlConnection(connString))
    using (var cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.AddWithValue("@name", name);
        conn.Open();
        using (var reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                nation = new Nation
                {
                    Id = reader.GetInt32(0),
                    NationName = reader.GetString(1)
                };
            }
        }
    }
    return nation; // 未找到返回 null
}

3. DAL 層:多條查詢返回集合

public List<Nation> GetAll()
{
    var list = new List<Nation>();
    const string sql = "SELECT Id, NationName FROM TB_Nation";

    using (var conn = new SqlConnection(connString))
    using (var cmd = new SqlCommand(sql, conn))
    {
        conn.Open();
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                list.Add(new Nation
                {
                    Id = reader.GetInt32(0),
                    NationName = reader.GetString(1)
                });
            }
        }
    }
    return list;
}

4. BLL 層:業務邏輯處理

public NationService
{
    private readonly NationDal _dal = new NationDal();

    public Nation FindByName(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("名稱不能為空");
        return _dal.GetByName(name.Trim());
    }
}

5. UI 層 (ASP.NET MVC Controller 示例)

public ActionResult Detail(string name)
{
    var service = new NationService();
    var nation = service.FindByName(name);
    if (nation == null) return HttpNotFound();
    return View(nation); // 自動綁定到 ViewModel
}

核心優勢

  • 類型安全:編譯期發現屬性拼寫錯誤
  • 資源自動釋放:using 確保連接/Reader 關閉
  • 防 SQL 注入:參數化查詢
  • 分層解耦:UI 不依賴 ADO.NET 細節

擴展建議

  • 使用 Dapper/EF Core 等 ORM 進一步簡化 DAL 代碼
  • 引入 Repository 模式 + 依賴注入,便於單元測試
  • 大數據量分頁查詢時返回 PagedResult<T> 包裝類

「返回實體類而非原始 DataReader」是從寫腳本走向工程化的關鍵一步。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved