C# Dapper 使用示範

安裝

先使用 NuGet 安裝 Dapper 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package Dapper
    

安裝對應資料庫的資料連接程式套件,以 SQL Server 為例:
	
dotnet add package System.Data.SqlClient
    

資料庫實體對應物件

    
public class UserEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
    

執行 SQL

使用參數執行 SQL,包括新增、更新、刪除,這裡是新增(insert)的示範:
    
string connectionString = "Server=192.168.0.2,1433;Database=my_database;User Id=sa;Password=password;";
using var connection = new SqlConnection(connectionString);

List<UserEntity> list = new()
{
    new()
    {
        Id = 1,
        Name = "小明",
        Email = "t1@email.com",
    },
    new()
    {
        Id = 2,
        Name = "老王",
        Email = "t2@email.com",
    }
};

int execute = connection.Execute(
    "INSERT INTO users (id, name, email) VALUES (@Id, @Name, @Email)",
    list
);

Console.WriteLine($"Execute: {execute}"); // Execute: 2
    

註: 若是使用 Oracle,結尾不可以加上分號,並且參數開頭不能使用 "@" ,可以使用 ":"

會自動依照屬性對應參數,如果只是暫時用的參數,並沒有建立相對應的物件,可以使用匿名類別,下面是一個更新的範例:
    
string connectionString = "Server=192.168.0.2,1433;Database=my_database;User Id=sa;Password=password;";
using var connection = new SqlConnection(connectionString);

int execute = connection.Execute(
    "UPDATE users SET name = @Name WHERE id = @Id",
    new
    {
        Id = 1,
        Name = "不是老王"
    }
);
    

查詢

    
string connectionString = "Server=192.168.0.2,1433;Database=my_database;User Id=sa;Password=password;";
using var connection = new SqlConnection(connectionString);

List<UserEntity> list = connection.Query<UserEntity>("SELECT * FROM users")
    .ToList();
    
foreach (var user in list)
{
    Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Email: {user.Email}");
}

// Id: 1, Name: 小明, Email: t1@email.com
// Id: 2, Name: 老王, Email: t2@email.com

    



參考資料:
Github - Dapper
Dapper

留言