Automapper配置文件不起作用

时间:2013-10-08 06:34:40

标签: c# automapper

有谁知道为什么会这样:

Mapper.Configuration.RecognizeDestinationPrefixes("Foo");
Mapper.CreateMap<A, B>();

但这不是:

Mapper.CreateProfile("FooPrefix").RecognizeDestinationPrefixes("Foo");
Mapper.CreateMap<A, B>()
      .WithProfile("FooPrefix");

2 个答案:

答案 0 :(得分:3)

虽然这个问题现在已经很老了,但我觉得回答它会很有用,因为我花了很多时间试图让个人资料工作。

虽然有很多方法可以配置配置文件,但似乎我可以让它工作的唯一方法如下:

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>());

给出Source和Destination类如下:

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

答案 1 :(得分:2)

个人资料名称不同。您在创建配置文件时使用FooxPrefix,然后在创建地图时使用FooPrefix。