C# 使用 Dapper-FluentMap 套件快速將查詢結果資料對應

註: Dapper.FluentMap 的 Github 儲存庫在 2023 年 4 月 19 日封存,未來很可能不會再更新。

安裝

Dapper.FluentMap 需要 Dapper 套件才能正常使用, 先使用 NuGet 安裝 Dapper.Dapper 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package Dapper
    

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

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

程式碼範例

假設我們有個基礎的使用者實體如下:
    
public class UserEntity
{
    public int Id { get; set; }
    public string UserName { get; set; }
}
    

資料表定義如下:
    
create table dbo.users
(
    id        int          not null
        primary key,
    user_name nvarchar(50) not null
)
    

會發現 UserName 和 user_name 對應不起來,使用平時的查詢語法 UserName 會是空白:
    
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 id, user_name from users")
    .ToList();
    

使用 Dapper-FluentMap

使用 Dapper-FluentMap 有兩步驟:
1. 依照對應的實體建立一個類別,在建構子使用 ToColumn 綁定資料表中的欄位名稱
    
public class UserEntityMap : EntityMap<UserEntity>
{
    public UserEntityMap()
    {
        Map(x => x.Id).ToColumn("id");
        Map(x => x.UserName).ToColumn("user_name");
    }
}
    

2. 在程式的一開始將我們建立好的 Map 類別加入
    
FluentMapper.Initialize(config =>
{
    config.AddMap(new UserEntityMap());
});
    

其他的不需要修改,直接查詢就會發現可以正常取得資料了!

不區分大小寫

假設今天取回來的欄位是大寫 USER_NAME ,而有的時候又是小寫 user_name 該怎麼辦?
只要在 ToColumn 的第二個參數設定為 false ,就可以忽略大小寫了,非常方便!
    
public class UserEntityMap : EntityMap<UserEntity>
{
    public UserEntityMap()
    {
        Map(x => x.Id).ToColumn("id");
        Map(x => x.UserName).ToColumn("user_name", false);
    }
}
    



參考資料:
Github - Dapper.FluentMap

留言