2017-04-27 44 views
2

我想將Dapper數據映射到對象。但在映射到Dictionary對象時遇到問題。Slapper&Dapper字典支持

要求是將數據行映射到對象。

數據行

1 | Key1 | Value1

1 | Key2 |值2

期望值

標識 - >1

數據 - {{"Key1","Value1" }, { "Key2","Value2"}}

地圖代碼:

 IDictionary<string, object> entity = new Dictionary<string, object>(); 
     entity.Add("Id", "1"); 
     entity.Add("Data_Key", new List<string>() { "Key1", "Key2" }); 
     entity.Add("Data_Value", new List<string>() { "Value1", "Value2" }); 
     var result=Slapper.AutoMapper.Map<TestEntity>(entity); 

實體Ø bject

public class TestEntity 
{ 
    public int Id { get; set; } 
    public Dictionary<string,string> Data { get; set; } 
} 

有沒有辦法實現這個?

回答

0

我相信這是不可能的。
該字典數據包含KeyValuePairs。這些是結構(不可變的),因此成員是隻讀的。因此,Slapper無法設置它們,它們只能在通用的KeyValuePair構造函數中設置。

+0

是的..我無法通過直接映射來實現它。所以,我必須做一個解決方法(發佈)。 感謝您的幫助。 –

1

正如其他用戶提到的,它是不可能通過Slapper.Automapper實現的。

但是,我找到了一個解決方法來實現它。

我已經創建了一個TypeConverter,它接受一個JSON字符串並返回一個Dictionary對象。

public class DictionaryConverter : ITypeConverter 
{ 
    public int Order => 110; 

    public bool CanConvert(object value, Type type) 
    { 
     // Handle Nullable types 
     var conversionType = Nullable.GetUnderlyingType(type) ?? type; 
     //Check if Type is a Dictionary 
     return conversionType.IsGenericType && conversionType.GetGenericTypeDefinition() == typeof(Dictionary<,>); 
    } 

    public object Convert(object value, Type type) 
    { 
     // Handle Nullable types 
     var conversionType = Nullable.GetUnderlyingType(type) ?? type; 
     //Create Empty Instance 
     object result = Activator.CreateInstance(type); 
     if (value != null) 
     { 
      try 
      { 
       result = JsonConvert.DeserializeObject(value as string, type); 
      } 
      catch (JsonException ex) 
      { 
       throw new Exception("Invalid JSON String while Converting to Dictionary Object", ex); 
      } 
     } 
     return result; 
    } 
}