- 主要有時後回傳 Column 的名稱,不好閱讀或者是中文,因此想要重新命名,但通常需要修改 SQL 語法,如不想修改 SQL 語法,可使用此方法
- 實作 SqlMapper.ITypeMap
- 將 ColumnAttributeTypeMapper.cs 實作至專案中
-- =============================================
-- Author: Lyndonliu
-- =============================================
ALTER PROCEDURE [dbo].[SP_DemoGetUserInfo]
AS
BEGIN
SELECT
UserInfo.Name AS '姓名',
UserInfo.Age AS '年齡'
FROM UserInfo
END
- 資料結構 member
- Add [Column(Name = "ColumnName")] info
- Code
using CustomColumnLibrary.Infrastructure;
namespace CustomColumnLibrary.Models
{
///
/// User Info
///
public class User
{
///
/// User Name
///
[Column(Name = "姓名")]
public string Name { get; set; }
///
/// User Age
///
[Column(Name = "年齡")]
public int Age { get; set; }
}
}
Dapper 查詢
- Add Dapper.SqlMapper.SetTypeMap Info
- Code
List< User> lUser = null;
using (SqlConnection con = new SqlConnection(Info.LyndonliuConnectionString))
{
// 呼叫 Dapper.SqlMapper.SetTypeMap
// 對應的類別跟欄位映射丟進去就可以了
Dapper.SqlMapper.SetTypeMap(typeof(User), new ColumnAttributeTypeMapper< User>());
// 執行 Query
lUser = con.Query< User>("SP_DemoGetUserInfo",
commandType: CommandType.StoredProcedure,
commandTimeout: 0).ToList();
}
- 方法比較
- Ref
- https://dotblogs.com.tw/supershowwei/2016/08/16/175753
- https://gist.github.com/kalebpederson/5460509
沒有留言:
張貼留言