是的,AutoMapper可以从Dictionary
using AutoMapper;
using System;
using System.Collections.Generic;
namespace AutoMapperExample
{
public class Source
{
public Dictionary Properties { get; set; }
}
public class Destination
{
public int IntProperty { get; set; }
public string StringProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
// 创建映射配置
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap, Destination>()
.ForMember(dest => dest.IntProperty, opt => opt.MapFrom(src => Convert.ToInt32(src["IntProperty"])))
.ForMember(dest => dest.StringProperty, opt => opt.MapFrom(src => src["StringProperty"].ToString()));
});
// 创建映射器
var mapper = config.CreateMapper();
// 创建源对象
var source = new Source
{
Properties = new Dictionary
{
{ "IntProperty", 10 },
{ "StringProperty", "Hello, AutoMapper!" }
}
};
// 执行映射
var destination = mapper.Map(source.Properties);
// 输出映射结果
Console.WriteLine($"IntProperty: {destination.IntProperty}");
Console.WriteLine($"StringProperty: {destination.StringProperty}");
}
}
}
在上面的示例中,我们创建了一个Source类和一个Destination类,其中Source类包含一个Dictionary
输出结果应为: IntProperty: 10 StringProperty: Hello, AutoMapper!