首頁  >  文章  >  後端開發  >  C# | Dapper 使用預存程序

C# | Dapper 使用預存程序

王林
王林原創
2024-07-24 09:47:13966瀏覽

C# | Dapper Using Stored Procedures

Note
You can check other posts on my personal website: https://hbolajraf.net

介紹

Dapper 是一個簡單、輕量級的 .NET 物件關係映射 (ORM) 函式庫。它旨在提供高效能並減少通常與傳統 ORM 相關的開銷。 Dapper 的強大功能之一是它支援執行預存程序。在本指南中,我們將探索如何透過 Dapper 在 C# 中使用預存程序。

先決條件

開始之前,請確保您已安裝以下軟體:

  • 精緻的 NuGet 包
  • SQL Server 或其他具有預存程序的資料庫

範例:基本設定

using System;
using System.Data;
using System.Data.SqlClient;
using Dapper;

class Program
{
    static void Main()
    {
        // Connection string for your database
        string connectionString = "YourConnectionStringHere";

        using (IDbConnection dbConnection = new SqlConnection(connectionString))
        {
            // Example of calling a stored procedure with Dapper
            var result = dbConnection.Query<int>("YourStoredProcedureName", commandType: CommandType.StoredProcedure);

            // Process the result as needed
            foreach (var value in result)
            {
                Console.WriteLine(value);
            }
        }
    }
}

在此範例中,將 YourConnectionStringHere 替換為您的實際資料庫連接字串,將 YourStoredProcedureName 替換為您的預存程序的名稱。

範例:帶參數的預存程序

using System;
using System.Data;
using System.Data.SqlClient;
using Dapper;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

        using (IDbConnection dbConnection = new SqlConnection(connectionString))
        {
            // Parameters for the stored procedure
            var parameters = new { Param1 = "Value1", Param2 = 42 };

            // Example of calling a stored procedure with parameters using Dapper
            var result = dbConnection.Query<int>("YourStoredProcedureName", parameters, commandType: CommandType.StoredProcedure);

            foreach (var value in result)
            {
                Console.WriteLine(value);
            }
        }
    }
}

在此範例中,定義預存程序的參數並將 Value1 和 42 替換為實際值。

接下來做什麼?

Dapper 讓 C# 中的預存程序的使用變得簡單。它提供了一種使用最少量程式碼與資料庫互動的乾淨而有效的方法。嘗試提供的範例並使其適應您的特定用例,以便在您的 C# 專案中利用 Dapper 的強大功能。

以上是C# | Dapper 使用預存程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C# |常見錯誤下一篇:C# |常見錯誤