我正在尝试将Dapper数据映射到对象。但是在映射到Dictionary对象时遇到问题。
要求是将数据行映射到对象。
数据行
1 | Key1 |值1
1 | Key2 |值2
预期值
Id - > 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);
实体对象
public class TestEntity
{
public int Id { get; set; }
public Dictionary<string,string> Data { get; set; }
}
有没有办法实现这个目标?
答案 0 :(得分:1)
正如其他用户所说,通过Slapper.Automapper无法实现它。
但是,我找到了解决方法来实现它。
我创建了一个TypeConverter,它接受一个JSON String并返回一个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;
}
}
答案 1 :(得分:0)
我认为这是不可能的 字典数据包含 KeyValuePairs 。这些是结构(不可变),因此成员 Key 和 Value 是只读的。因此Slapper无法设置它们,只能在通用 KeyValuePair 构造函数中设置它们。