【问题标题】:Slapper & Dapper Dictionary SupportSlapper & Dapper 字典支持
【发布时间】:2017-04-27 05:15:14
【问题描述】:

我正在尝试将 Dapper 数据映射到一个对象。但是在映射到 Dictionary 对象时遇到了问题。

要求是将数据行映射到对象。

数据行

1 |键1 |价值1

1 |键2 |价值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; }
}

有没有办法做到这一点??

【问题讨论】:

    标签: c# .net automapper dapper slapper.automapper


    【解决方案1】:

    正如其他用户所说,通过Slapper.Automapper是不可能实现的。

    但是,我找到了实现它的解决方法。

    我创建了一个 TypeConverter,它接受一个 JSON 字符串并返回一个字典对象。

    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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      我相信这是不可能的。
      字典 Data 包含 KeyValuePairs。这些是结构(不可变),因此成员 KeyValue 是只读的。因此 Slapper 无法设置它们,它们只能在通用 KeyValuePair 构造函数中设置。

      【讨论】:

      • 是的..我无法通过直接映射来实现它。所以,我不得不做一个解决方法(已发布)。感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 2015-02-17
      • 1970-01-01
      • 2019-05-03
      • 2021-01-30
      • 2022-11-19
      • 1970-01-01
      相关资源
      最近更新 更多