2015-06-08 66 views
1

我有類似下面的詞典:如何在C#中使用Dapper將對象放入字典中?

Dictionary<string,SP> dict; 

包含字符串和SP對象。

我想做到以下幾點

dict = conn.Query("SELECT routine_name,created,modified FROM PROCEDURES").toDictionary (
         row => (string)row.Routine_Name, 
         row => new SP (Name=row.Routine_Name,Created=row.created,Modified=row.modified)); 

上面的代碼無法正常工作。我如何用上面的信息創建一個SP對象。我有一個構造函數,它接受這三個參數。

回答

4
  1. 創建適當的模型

    public class SP { 
        public string RoutineName { get; set; } 
        public DateTime Created { get; set; } 
        public DateTime Modified { get; set; } 
    } 
    
  2. 地圖查詢到性能建模,選擇它以字典

    Dictionary<string, SP> dictionary = connection.Query<SP>(@" 
        SELECT 
         routine_name AS RoutineName, 
         created AS Created, 
         modified AS Modified 
        FROM PROCEDURES 
    ").ToDictionary(m => m.RoutineName, m => m); 
    
+0

請問這仍然工作,如果SP包含一個構造函數呢? – regal

+0

@regal它也必須有一個無參數的構造函數。 – juharr