有人知道为什么这个代码可以运行吗:
Mapper.Configuration.RecognizeDestinationPrefixes("Foo");
Mapper.CreateMap<A, B>();
但是这个却不行:
Mapper.CreateProfile("FooPrefix").RecognizeDestinationPrefixes("Foo");
Mapper.CreateMap<A, B>()
.WithProfile("FooPrefix");
?
有人知道为什么这个代码可以运行吗:
Mapper.Configuration.RecognizeDestinationPrefixes("Foo");
Mapper.CreateMap<A, B>();
Mapper.CreateProfile("FooPrefix").RecognizeDestinationPrefixes("Foo");
Mapper.CreateMap<A, B>()
.WithProfile("FooPrefix");
?
虽然这个问题现在已经很老了,但考虑到我花费了很长时间来使配置文件正常工作,我认为回答这个问题还是有用的。
尽管有很多配置配置文件的方法,但似乎我能让它正常工作的唯一方法如下:
public class ExampleProfile : Profile
{
protected override void Configure()
{
ReplaceMemberName("Z", "A");
CreateMap<Source, Destination>(); // Notice this is CreateMap, NOT Mapper.CreateMap...
}
public override string ProfileName
{
get { return this.GetType().Name; }
}
}
然后,在您的配置文件中设置配置文件:
Mapper.Initialize(cfg => cfg.AddProfile<ExampleProfile>());
假设有以下源和目标类:
public class Source
{
public string Zabc { get; set; }
}
public class Destination
{
public string Aabc { get; set; }
}
现在应该可以正常工作了:
var source = new Source { Zabc = "source" };
var dest = Mapper.Map<Destination>(source);
Assert.AreEqual(source.Zabc, dest.Aabc);
配置文件名称不同。创建配置文件时使用FooxPrefix,创建地图时则使用FooPrefix。