我正在连接一些WebService并接收Dictionary 包含键:“firstName”,“lastName”,“otherfirstName”,“otherLastName”。
我有对象人
public class Person
{
public string FirstName{get;set;}
public string LastName{get;set;}
}
根据某些上下文,我应该通过映射“firstName”和“lastName”中的值来创建我的对象Person,在另一种情况下,通过映射来自“otherfirstName”和“otherlastName”
如果我只能创建一个映射函数,我如何映射到其他人并动态地在它们之间进行更改?
Mapper.CreateMap<Response, Person>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.Dict["firstName"] : "") ))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.Dict["lastName"] : "") ));
我在Profiles中看到了一些用法,但我不确定如何在我的情况下使用它。
被修改
public class FirstMapper : Profile
{
protected override void Configure()
{
base.Configure();
Mapper.CreateMap<Src, Person>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.Dct["firstName"]))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.Dct["lastName"]));
}
}
public class SecondMapper : Profile
{
protected override void Configure()
{
base.Configure();
Mapper.CreateMap<Src, Person>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.Dct["otherfirstName"]))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.Dct["otherlastName"]));
}
}
public class Src
{
public Dictionary<string, string> Dct { get; set; }
}
我的测试课
public class Test
{
public Test()
{
Src src = new Src();
src.Dct = new Dictionary<string, string>();
src.Dct["firstName"] = "La";
src.Dct["lastName"] = "Nu";
src.Dct["otherfirstName"] = "Fe";
src.Dct["otherlastName"] = "oooo";
Person person = new Person();
ConfigurationStore store = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers);
store.AssertConfigurationIsValid();
MappingEngine engine = new MappingEngine(store) ;
//add mappings via Profiles or CreateMap
store.AddProfile(new FirstMapper());
person = engine.Map<Person>(src);
}
我在最后一行有异常:“”缺少类型映射配置或不支持的映射.......“