2017年7月28日 星期五

[C#] Custom column using Dapper (3)

  • Dapper.FluentColumnMapping

  • 安裝中發生錯誤
    • .Net Framework 4.5 版本不支援 
    • 查看官網資訊(Dependencies: .NETFramework 4.5.1, Dapper (>= 1.42.0))
    • 需要將 .Net Framework 4.5 變更為 .NETFramework 4.5.1
    • 如 Dapper.1.50.2 版本,將會發生 Warring 

  • Sql 資料
  • -- =============================================
    -- Author:  Lyndonliu
    -- =============================================
    ALTER PROCEDURE [dbo].[SP_DemoGetUserInfo]
    
    AS
    BEGIN
     SELECT 
     UserInfo.Name AS '姓名',
     UserInfo.Age AS '年齡'
     FROM UserInfo
    END
    
  • 資料結構 
    • Code
    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 查詢
    • Code
    
                    List< User> lUser = null;
                    using (SqlConnection con = new SqlConnection(Info.LyndonliuConnectionString))
                    {
                        // 欄位對應
                        ColumnMappingCollection columnMappings = new ColumnMappingCollection();
    
                        columnMappings.RegisterType< User>()
                                      .MapProperty(x => x.Name).ToColumn("姓名")
                                      .MapProperty(x => x.Age).ToColumn("年齡");
    
                        columnMappings.RegisterWithDapper();
    
                         // 執行 Query
                        lUser = con.Query< User>("SP_DemoGetUserInfo",
                                            commandType: CommandType.StoredProcedure,
                                            commandTimeout: 0).ToList();
                    }
    
  • 此方法最不推薦,因需修改 .Net Framework 4.5.1 與所支援的  Dapper 為舊版本
  • Ref
    • https://dotblogs.com.tw/supershowwei/2016/08/16/175753

沒有留言:

張貼留言